FactoryGirl association model trouble: “SystemStackError: stack level too deep”

后端 未结 2 1965
迷失自我
迷失自我 2020-12-16 00:33

I am using Ruby on Rails 3.0.9, RSpec-rails 2 and FactoryGirl. I am trying to state a Factory association model but I am in trouble.

I have a factories/user.rb

2条回答
  •  没有蜡笔的小新
    2020-12-16 01:13

    Spyle's excellent answer (still working with Rails 5.2 and RSpec 3.8) will work for most associations. I had a use case where a factory needed to use 2 different factories (or different traits) for a single has_many association (ie. for a scope type method).

    What I ended up coming up with was:

    # To build user with posts of category == 'Special' and category == 'Regular'
    after(:create) do |user, evaluator|
      array = []
      array.push(FactoryBot.create_list(:post, 1, category: 'Regular')
      array.push(FactoryBot.create_list(:post, 1, category: 'Special')
      user.posts = array.flatten
    end
    

    This allowed the user to have 1 post of category 'Regular' and 1 post of category 'Special.'

提交回复
热议问题