3

我有 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 中 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

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

nil:NilClass (NoMethodError) 的未定义方法“查找”未定义

nil 的方法“文章”:NilClass (NoMethodError)

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

4

1 回答 1

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
于 2012-06-08T17:38:57.197 回答