rspec与工厂女孩

时间:2011-08-15 06:45:11

标签: ruby-on-rails rspec factory-bot

我有以下工厂:

Factory.define :producer, :class => User do |f|
  f.sequence(:email) { |n| "producer_#{n}@shit.com" }
  f.password  "foobar"
  f.password_confirmation "foobar"
  f.role      "producer"
end

Factory.define :business do |f|
  f.sequence(:name) { |n| "business_#{n}" }
  f.association(:producer, :factory => :producer)
end

Factory.define :deal do |d| 
  d.sequence(:title) { |n| "deal_#{n}" }
  d.sequence(:desc) { |n| "deal_desc_#{n}" }
  d.cap "50" 
  d.rate "2" 
  d.start Date.today - 1     # This is the date where you put in db
  d.end Date.today + 7
  d.association :business
end

现在当我执行以下操作时:

  before(:each) do 
    @consumer = test_sign_in(Factory(:consumer))
    @deal = Factory(:deal)
  end

我收到错误:

 Failure/Error: @deal = Factory(:deal)
 NoMethodError:
   undefined method `producer=' for #<Business:0x007fb494290090>
 # ./deals_controller_spec.rb:15:in `block (4 levels) in <top (required)>

(第15行引用@deal = Factory(:deal)

有谁知道为什么?我是工厂女孩的新手,我似乎无法找到解释关联和序列的文档。

1 个答案:

答案 0 :(得分:1)

此处的问题显然与您的producer关联的创建有关。

由于您使用的是旧的dsl,我建议使用两种解决方案:

Factory.define :business do |f|
  f.sequence(:name) { |n| "business_#{n}" }
  #try this:
  f.association(:user, :factory => :producer)
  #or this:
  f.after_build { |biz| biz.user = Factory.build(:producer) }
end

使用after_buildafter_create实际上是一个选择问题,具体取决于您的测试目的。

Here is a link to the new dsl lookup