2012-04-08 58 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中类别#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 

无论是评论和注释掉测试产生此错误:

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

method 'articles' for nil:NilClass (NoMethodError)

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

回答

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

如果我想从不同的加工商创建文章/类别? – Luccas 2013-06-04 04:35:57