【问题标题】:Multithreaded ActiveRecord requests in rspecrspec 中的多线程 ActiveRecord 请求
【发布时间】:2011-02-19 22:42:29
【问题描述】:

我正在尝试在测试中重新创建竞争条件,因此我可以尝试一些解决方案。我发现在我在测试中创建的线程中,ActiveRecord 总是返回 0 的计数和 nil 的查找。例如,表“foos”中有 3 行:

  it "whatever" do
    puts Foo.count
    5.times do
      Thread.new do
        puts Foo.count
      end
    end
  end

将打印

3
0
0
0
0
0

test.log 显示预期的查询,预期的 6 次:

 SELECT count(*) AS count_all FROM `active_agents`

知道这里发生了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord multithreading rspec


    【解决方案1】:

    我假设 ActiveRecord 为每个线程打开一个专用的数据库连接。由于每个 RSpec 示例都包装在事务中,因此其他线程可能看不到更改。

    尝试禁用该规范的事务性固定装置。

    describe "thread test" do
      self.use_transactional_fixtures = false
    
      it "whatever" do
        puts Foo.count
        5.times do
          Thread.new do
            puts Foo.count
          end
        end
      end
    end
    

    【讨论】:

    • 我遇到了 jeem 描述的同样问题,@henning-koch 的解决方案为我解决了这个问题。我在上面的解决方案中添加了代码(不过需要被其他人接受)。
    • 我们在使用self.use_transactional_tests 时解决了这个问题。这是最新的 Rails 版本。
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多