Factory already registered: user (FactoryGirl::DuplicateDefinitionError)

后端 未结 27 2205
我在风中等你
我在风中等你 2021-02-06 21:18

Description of problem: - I\'ve setup factory_girl_rails however whenever I try and load a factory it\'s trying to load it multiple times.

Envir         


        
27条回答
  •  不思量自难忘°
    2021-02-06 21:37

    I solved this because I was trying to create two factories. My feature spec included the line:

    let!(:user) { create(:user) }
    

    And then I used a sign_up(user) helper method:

    def sign_up(user)
      visit '/users/sign_up'
      fill_in 'Email', with: user.email
      fill_in 'Password', with: user.password
      fill_in 'Password confirmation', with: user.password_confirmation
      click_button 'Sign up'
    end
    

    Back to my feature spec, I called:

    context 'logging out' do
      before do
        sign_up(user)
      end
    
    ...
    

    thus effectively trying to sign up a User that was already being created by the factory.

    I altered the sign_up(user) to sign_in(user), and the helper to:

    def sign_in(user)
      visit '/users/sign_in'
      fill_in 'Email', with: user.email
      fill_in 'Password', with: user.password
      click_button 'Log in'
    end 
    

    now the user argument creates the User in the db due to the let! block and the sign_up(user) logs them in.

    Hope this helps someone!

    oh! and I also had to comment out:

    Dir[Rails.root.join('spec/factories/**/*.rb')].each { |f| require f }
    

    as a lot of the other answers suggest.

提交回复
热议问题