2
votes

I am receiving the following error when testing a listing of books, that belong_to authors.

Failure/Error: visit books_path
     ActionView::Template::Error:
       undefined method `name' for nil:NilClass
     # ./app/views/books/_book.html.erb:5:in `_app_views_books__book_html_erb___3197212671375452820_30961180'
     # ./app/views/books/index.html.erb:8:in `_app_views_books_index_html_erb__3030997400964951224_38341240'
     # ./spec/requests/book_pages_spec.rb:13:in `block (3 levels) in <top (required)>'

I've been trying to debug it for 2 days without success and I am now turning to SO for some help.

I must point out that Book#index displays all the books correctly, the bug is probably just in my tests. I think factory girl isn't creating the associations correctly, since book.author returns nil.

Thank you!

book.rb

class Book < ActiveRecord::Base
  attr_accessible :title
  belongs_to :author    
  validates :author_id, presence: true
end

author.rb

class Author < ActiveRecord::Base
  attr_accessible :name
  has_many :books, dependent: :destroy
end

factories.rb

FactoryGirl.define do
  factory :author do
    sequence(:name) { |n| "Author #{n}" }
  end

  factory :book do
    sequence(:title) { |n| "Lorem ipsum #{n}" }
    author
  end
end

_book.html.erb

<li>
  <span class="title"><%= link_to book.title, book_path(book) %></span>
    <span class="author"><%= link_to book.author.name, author_path(book.author) %></span>
</li>

book_pages_spec.rb

require 'spec_helper'
describe "Book pages" do
  subject { page }
  describe "index" do
    let(:author) { FactoryGirl.create(:author) }
    before(:each) do
      visit books_path
    end
    before(:all) { 32.times {FactoryGirl.create(:book, author: author)} }
    after(:all) { Author.delete_all }
    it { should have_title_and_heading("All books") }
  end
end
1
Not sure why this question is showing up under "new', but if you're still there and still interested, the backtrace shows an error at line 5 of _book.html.erb, but you only show a 4-line file.Peter Alfvin

1 Answers

2
votes

In your after(:all) step you're clearing out the authors, but not the books that got created in the before(:all) step. Since the before/after :all hooks get run outside any transactions in the tests, you may well have stale data left in your test database.