【问题标题】:Why undefined method "has_many" in Rspec example?为什么在 Rspec 示例中未定义方法“has_many”?
【发布时间】:2011-09-22 10:12:29
【问题描述】:

我正在玩一个通过 RSpec 中的关联测试 has_many 的示例。 我得到了一个

1) Foo 指定项目 失败/错误:subject.should have_many(:items) 无方法错误: 未定义的方法“has_many?”为了 # # ./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

【问题讨论】:

    标签: activerecord rspec


    【解决方案1】:

    好吧,模型对象上没有has_many? 方法。而rspec-rails 默认不提供这样的匹配器。但是,shoulda-matchers gem 可以:

    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
    

    (来自 shoulda-matchers documentation 的示例)

    只需将gem 'shoulda-matchers' 添加到您的Gemfile,您就可以使用该语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多