简体   繁体   中英

Rspec and FactoryGirl: SystemStackError: stack level too deep rails

I have one spec and one factory and I am getting this error:

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

When I try to use the verbage 'build' it works; but I need it to save to test data and 'create' doesn't work in let!(:user) { create(:user) } as it sets off that error. Rspec seems to work fine.

I am running ruby 2.2.2; using rspec, and factory girl

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

To setup associations you can just call the name of the factory:

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

Never hardcode IDs into your factories - you're only setting yourself up for a world of hurt.

If you are using Rolify you can use a callback to add a role to a user instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM