Rspec and FactoryGirl: SystemStackError: stack level too deep rails

Rspec and FactoryGirl: SystemStackError: stack level too deep rails

我有一个规格和一个工厂,但出现此错误:

SystemStackError: stack level too deep
    from gems/activerecord-4.2.1/lib/active_record/relation/delegation.rb:9:in `relation_delegate_class'    

当我尝试使用动词 'build' 时,它起作用了;但我需要它来保存测试数据,并且 'create' 在 let!(:user) { create(:user) } 中不起作用,因为它会引发该错误。 Rspec 似乎工作正常。

我是运行ruby2.2.2;使用 rspec 和工厂女孩

require 'spec_helper'
describe API::V1::CurrentUserController do
   let!(:user) { create(:user) }
    setup_api_authorization

   describe "GET 'show'" do
    before (:each) do
    setup_api_headers
    get 'show', subdomain: 'api', id: 'me'
   end
end


FactoryGirl.define do
  factory :user, aliases: [:participant] do
    sequence(:email) { |n| "user#{n}@example.com" }
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    password 'testpass'
    password_confirmation { |user| user.password }
    role_id {4}
 end
end

要设置关联,您只需调用工厂名称即可:

FactoryGirl.define do
  factory :user, aliases: [:participant] do
    sequence(:email) { |n| "user#{n}@example.com" }
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    password 'testpass'
    password_confirmation { password  }
    role
  end
end

切勿将 ID 硬编码到您的工厂中 - 您只会让自己陷入痛苦的境地。

如果您使用的是 Rolify,则可以使用回调来为用户添加角色:

FactoryGirl.define do
  factory :user, aliases: [:participant] do
    sequence(:email) { |n| "user#{n}@example.com" }
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    password 'testpass'
    password_confirmation { password }
    after(:create) { |user| user.add_role(:peasant) }
  end
end

This error generally happens when you accidentally recursively changing an attribute. If you have a username attribute in User model, and a virtual attribute named username, that is directly changing the username, you end up calling the virtual, the virtual calls the virtual again and so on.. Therefore, take a look on whether something like that happens somewhere in your code.

Stack level too deep error in Ruby on Rails