2012-04-08 46 views
3

私が持っている2 HABTMモデル:FabricationとRSpecを使用してhas_and_belongs_to_many(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内の記事オブジェクトの存在を確認するテスト

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 

両方ともコメントとコメントのないテストがこのエラーを生成します。

undefined method 'find' for nil:NilClass (NoMethodError) undefined

method 'articles' for nil:NilClass (NoMethodError)

私はその逆、私は製作Categoryオブジェクト内の最初の記事のオブジェクトにアクセスすることができるとするにはどうすればよいですか?

答えて

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

また、別のFabricatorから記事/カテゴリを作成したいのですか? – Luccas

関連する問題