ruby-on-rails - rspec工厂女孩协会

标签 ruby-on-rails rspec associations factory-bot

在测试属于作者的书籍列表时,我收到以下错误。

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

我已经尝试调试它两天了,但没有成功,现在我向 SO 寻求帮助。

我必须指出 Book#index 正确显示所有书籍,该错误可能只是在我的测试中。我认为工厂女孩没有正确创建关联,因为 book.author 返回 nil。

谢谢!

书.rb

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

作者.rb

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

工厂.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

最佳答案

after(:all) 步骤中,您将清除作者,但不会清除在 before(:all) 步骤中创建的图书。由于 before/after :all Hook 在测试中的任何事务之外运行,因此您的测试数据库中很可能会留下过时的数据。

关于ruby-on-rails - rspec工厂女孩协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922256/

相关文章:

JPA 查询多对一关联

ruby-on-rails - rails : Friendly_id does not generate slugs for old records

ruby-on-rails - Rails Date.today 反射(reflect)了服务器部署日期

ruby-on-rails - Selenium rails 测试中的 Chromedriver 错误

ruby-on-rails - 如何格式化多行 RSpec expect {}.to change

dependencies - 关联是否意味着 UML 中的依赖关系?

ruby-on-rails - 继承自类模块

ruby-on-rails - 如何将回形针 before_post_process 与多个附件一起使用?

ruby-on-rails - 在 Rails 中自动测试流程

ruby-on-rails - rails 中的私有(private)协会