Nick
Nick

Reputation: 3090

Undefined method error but only in test

The test below generates the error message

ActionView::Template::Error: undefined method `avatar?' for nil:NilClass
app/views/members/index.html.erb:25:in `block in _app_views_members_index_html_erb___1876261578458959373_9315040'
app/views/members/index.html.erb:22:in `_app_views_members_index_html_erb___1876261578458959373_9315040'
test/integration/site_layout_test.rb:50:in `block in <class:SiteLayoutTest>'

Yet in development it seems to work. The avatar shows if present. Anyone got an idea about the cause?

The test:

get users_path
assert_template 'users/index'
User.paginate(page: 1).each do |user|
  assert_select 'a[href=?]', user_path(user)

get organizations_path
assert_template 'organizations/index'
Organization.paginate(page: 1).each do |organization|
  assert_select 'a[href=?]', organization_path(organization)
end

get members_path        # THIS IS LINE 50!!
assert_template 'members/index'
Member.paginate(page: 1).each do |member|
  assert_select 'a[href=?]', member_path(member)
end

Members index view includes:

<% @members.each do |member| %>    # THIS IS LINE 22!!
  <tr>
    <td>
      <% if member.organization.avatar? %>      # THIS IS LINE 25!!
        <%= link_to image_tag(member.organization.avatar.url, alt: "Profile"), member_path(member) %> <%= member.username %>
      <% else %>
        <%= link_to image_tag("profile.gif", alt: "Profile"), member_path(member) %> <%= member.username %>
      <% end %>
    </td>
    <td><%= member.fullname %></td>
    etc...

Upvotes: 1

Views: 118

Answers (2)

Codeguru
Codeguru

Reputation: 11

Remove the question mark

a[href=?]

should be

a[href]

Upvotes: 0

mikej
mikej

Reputation: 66263

This error means you've tried to call avatar? on nil.

The most likely cause is you have a member without an organization in your fixtures so that member.organization evaluates to nil.

Upvotes: 2

Related Questions