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

时间:2012-04-08 09:28:24

标签: ruby-on-rails rspec 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

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

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

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

我试图编写一个测试来检查RSpec中类别#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

评论和未评论的测试都会产生此错误:

  

未定义的方法&#39;找到&#39; for nil:NilClass(NoMethodError)undefined

     

方法&#39;文章&#39; for nil:NilClass(NoMethodError)

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

1 个答案:

答案 0 :(得分: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