2011-09-22 69 views
4

我正在玩一个关于在RSpec中通过关联测试has_many的例子。 我得到一个为什么在Rspec示例中未定义的方法“has_many”?

 
    1) Foo specifies items 
     Failure/Error: subject.should have_many(:items) 
     NoMethodError: 
     undefined method `has_many?' for # 
     # ./spec/models/foo_spec.rb:10 

我的问题:为什么会HAS_MANY是不确定的?

该规范是:

describe Foo do 
    it "specifies items" do 
    subject.should have_many(:items) 
    end 
end 

我的车型有:

foo.rb:

class Foo < ActiveRecord::Base 
    has_many :bars 
    has_many :items, :through => :bars 
end 

bar.rb:

class Bar < ActiveRecord::Base 
    belongs_to :foo 
    belongs_to :item 
end 

和item.rb的:

class Item < ActiveRecord::Base 
    has_many :foos, :through => :bars 
    has_many :bars 
end 

回答

8

那么,模型对象上没有has_many?方法。而rspec-rails默认不提供这种匹配器。然而,shoulda-matchers宝石的作用:

describe Post do 
    it { should belong_to(:user) } 
    it { should have_many(:tags).through(:taggings) } 
end 

describe User do 
    it { should have_many(:posts) } 
end 

(例如,从早该-的匹配documentation

只需添加gem 'shoulda-matchers'Gemfile,你将能够使用这种语法。

相关问题