在 Rspec 中创建的记录在新线程中不可用?

Records created in Rspec aren't available in new threads?

在 Rspec 中,我正在创建记录,例如let!(:user) { create(:user) }.

我可以在Rspec和主题的主线程中访问新用户。这两个 return 用户:

puts User.all.to_a
puts ActiveRecord::Base.connection.exec_query('select * from users')

但是,我现在可以在新线程中访问用户了:

Thread.new do
    puts User.all.to_a
    puts ActiveRecord::Base.connection.exec_query('select * from users')
end

我该如何解决这个问题?这只是一个 Rspec 问题吗?我不认为我可以在 Rails 控制台中重现它。

您可能已经将 RSpec 配置为 运行 它在数据库事务中的测试

引自RSpec Docs: >

When you run rails generate rspec:install, the spec/rails_helper.rb file includes the following configuration:

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

The name of this setting is a bit misleading. What it really means in Rails is "run every test method within a transaction." In the context of rspec-rails, it means "run every example within a transaction."

The idea is to start each example with a clean database, create whatever data is necessary for that example, and then remove that data by simply rolling back the transaction at the end of the example.

当您的应用程序测试需要同时支持多个线程时,您可能希望禁用此配置。

但这意味着当测试完成后,您的测试数据库将不再自动从测试数据中清除。相反,您将需要手动删除测试数据或使用另一个 gem(如 database_cleaner)在 运行ning 测试后重置数据库。