如何使用Fabrication和RSpec制作和测试has_and_belongs_to_many(HABTM)关联?

Ter*_*nce 3 rspec ruby-on-rails capybara fabrication-gem

我有2个HABTM型号:

class Article < ActiveRecord::Base
  attr_accessible :title, :content
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  has_and_belongs_to_many :categories

  validates :title, :presence => true
  validates :content, :presence => true
  validates :author_id, :presence => true

  default_scope :order => 'articles.created_at DESC'
end

class Category < ActiveRecord::Base
  attr_accessible :description, :name
  has_and_belongs_to_many :articles

  validates :name, :presence => true
end
Run Code Online (Sandbox Code Playgroud)

Article 属于作者(用户)

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me
  attr_accessible :name

  has_many :articles, :foreign_key => 'author_id', :dependent => :destroy
end
Run Code Online (Sandbox Code Playgroud)

与他们各自的制造商一起:

Fabricator(:user) do
  email { sequence(:email) { |i| "user#{i}@example.com" } }
  name { sequence(:name) { |i| "Example User-#{i}" } }
  password 'foobar'
end

Fabricator(:article) do
  title 'This is a title'
  content 'This is the content'
  author { Fabricate(:user) }
  categories { Fabricate.sequence(:category) }
end

Fabricator(:category) do
  name "Best Category"
  description "This is the best category evar! Nevar forget."
  articles { Fabricate.sequence(:article) }
end
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个测试来检查RSpec中Category#show中是否存在Article对象

before do
  @category = Fabricate(:category)
  visit category_path(@category)
end

# it { should have_link(@category.articles.find(1).title :href => article_path(@category.articles.find(1))) }
@category.articles.each do |article|
  it { should have_link(article.title, :href => article_path(article)) }
end
Run Code Online (Sandbox Code Playgroud)

注释和未注释的测试都会产生此错误:

未定义的方法'find'代表nil:NilClass(NoMethodError)undefined

nil的方法'articles':NilClass(NoMethodError)

我该怎么做才能访问我编造的Category对象中的第一个Article对象,反之亦然?

小智 6

无论何时调用Fabricate.sequence它都会返回一个整数,除非你传递一个块.您需要生成实际的相关对象.您应该像这样生成您的关联:

Fabricator(:article) do
  title 'This is a title'
  content 'This is the content'
  author { Fabricate(:user) }
  categories(count: 1)
end

Fabricator(:category) do
  name "Best Category"
  description "This is the best category evar! Nevar forget."
  articles(count: 1)
end
Run Code Online (Sandbox Code Playgroud)