2012-08-12 66 views
2

在測試屬於作者的書籍列表時,我收到以下錯誤。rspec factory girl associations

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)>' 

我一直在試圖調試它2天沒有成功,我現在轉向SO的一些幫助。

我必須指出,Book#index正確顯示所有書籍,這個錯誤可能只是在我的測試中。我認爲工廠女孩沒有正確創建關聯,因爲book.author返回nil。

謝謝!

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 
+0

不知道爲什麼這個問題顯示在「新」下,但如果你仍然在那裏,仍然有興趣,回溯顯示'_book.html.erb'第5行的錯誤,但你只顯示一個4在線文件。 – 2013-09-05 22:26:26

回答

2

在你after(:all)一步你清理出的作家,但不是說得到了在before(:all)步驟中創建的書籍。由於之前/之後:所有鉤子都會在測試中的任何事務之外運行,因此您的測試數據庫中可能會保留陳舊的數據。

相關問題