测试 FactoryGril 生成 model 数量不对

autumnwolf · 2015年09月14日 · 最后由 greatghoul 回复于 2015年09月15日 · 1911 次阅读

我用 FactoryGril 生成 2 个 User 然后每个有 3 个 event

let (:user) {FactoryGirl.create :user,:with_events}
    let (:user1) {FactoryGirl.create :user,:with_events}

但是测试生成的 events 数量的时候应该生成 6 个却是 3 个

Failure/Error: expect(json["events"].count).to eq 6

       expected: 6
            got: 3

       (compared using ==)

Factories.rb

FactoryGirl.define do |f|

  factory :user do
    password      "123123"
    sequence(:name){|n| "张三#{n}" }
  end

  factory :event do 
    end_date      "2015-05-30"
    is_countdown  "1"
  end


  trait :with_events do
    after :create do |user|
      FactoryGirl.create_list :event, 3, :user => user
    end
  end
end

谢啦!

看一下你对应的测试代码是不是 useruser1 只调用过一个。

Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked.

关于 let 和 let!: https://www.relishapp.com/rspec/rspec-core/v/3-3/docs/helper-methods/let-and-let

俺也感觉是使用了 let 但木有调用 useruser1 如果不测试 user相关,直接 before block 里面直接 create 好了

ps: 楼主可以省略掉每次输入 FactoryGirl

# RSpec
# spec/support/factory_girl.rb
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

#1 楼 @erithair 多谢 是的只调用了一个 换了 let!好用了!

#2 楼 @etnl 谢谢实际上我已经写了这个 同样感谢!

之前好像也遇到过类似的问题

create_list(:xxx, 3).tap({})
需要 登录 后方可回复, 如果你还没有账号请 注册新账号