jeem
jeem

Reputation: 919

Multithreaded ActiveRecord requests in rspec

I'm trying to recreate a race condition in a test, so I can try out some solutions. I find that in the threads I create in my test, ActiveRecord always returns 0 for counts and nil for finds. For example, with 3 rows in the table "foos":

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

will print

3
0
0
0
0
0

test.log shows the expected query, the expected 6 times:

 SELECT count(*) AS count_all FROM `active_agents`

Any idea what's going on here?

Upvotes: 9

Views: 4448

Answers (1)

triskweline
triskweline

Reputation: 1538

I'm assuming ActiveRecord opens a dedicated database connection for each thread. Since each RSpec example is wrapped inside a transaction, the other threads might not see the changes.

Try disabling transactional fixtures for that spec.

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

Upvotes: 17

Related Questions