【问题标题】:Getting unitialized constant when trying to create more than one user in factory_girl尝试在工厂女孩中创建多个用户时获得未初始化的常量
【发布时间】:2026-01-15 23:35:02
【问题描述】:

我正在尝试使用 factory girl 创建两个用户,每个用户都有不同的sign_in_count(使用设计)。到目前为止,第一个测试很好,但是当第二个测试时,我收到第二个用户未初始化的错误。如果重要的话,测试套件是 Test::Unit(不是 RSpec)。

这是测试

require 'test_helper'

class ApplicationControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

   test 'user should be redirected to profile edit on first login' do
     @user = create(:user, sign_in_count: 0)
     visit(new_user_session_path)
     fill_in('user_email', :with => @user.email)
     fill_in('user_password', :with => 'foobar')
     click_button('Log in')
     assert_current_path(edit_user_registration_path)
     logout(@user)
   end

   test 'user should be taken to root on subsequent logins' do
     @other_user = create(:other_user, sign_in_count: 5)
     visit(new_user_session_path)
     fill_in('user_email', :with => @other_user.email)
     fill_in('user_password', :with => 'foobar')
     click_button('Log in')
     assert_current_path(root_path)
   end
end

和工厂

FactoryGirl.define do
  sequence(:email) { |n| "person#{n}@example.com" }
  sequence(:id) { |n| n }

  factory :user do
    email
    password 'foobar'
    password_confirmation 'foobar'
    id
    after(:create) { |user| user.confirm }
  end

  factory :other_user do
    email
    password 'foobar'
    password_confirmation 'foobar'
    id
    after(:create) { |user| user.confirm }
  end
end

还有错误

ERROR["test_user_should_be_taken_to_root_on_subsequent_logins", ApplicationControllerTest, 0.8529229999985546]
 test_user_should_be_taken_to_root_on_subsequent_logins#ApplicationControllerTest (0.85s)
NameError:         NameError: uninitialized constant OtherUser
            test/controllers/application_controller_test.rb:17:in `block in <class:ApplicationControllerTest>'

【问题讨论】:

    标签: ruby-on-rails devise capybara factory-bot testunit


    【解决方案1】:

    FactoryGirl 尝试查找类名为 OtherUser 的模型。但是你没有那个模型。相反,您想使用 User 模型,但您使用的是不同的工厂名称。

    所以,添加类名将解决问题

    factory :other_user, class: User do
      email
      password 'foobar'
      password_confirmation 'foobar'
      id
      after(:create) { |user| user.confirm }
    end
    

    【讨论】:

    • 这行得通,谢谢!并感谢您的解释
    • 您也可能不想在工厂中设置 id,这将由数据库自动设置,在此示例中根本不需要 other_user 工厂——只需创建第二个用户实例
    • @oneWorkingHeadphone 是的,实际上你不需要新工厂
    • @ThomasWalpole 啊,是的,你是对的,那是我试图一起破解解决方案时留下的代码。谢谢你的收获!
    最近更新 更多