Mateusz Urbański
Mateusz Urbański

Reputation: 7892

Stubbing sleep method with Rspec.

I have method that looks like this:

until panel_import.completed?
  panel_import.update_status
  sleep 1.minute
end

Now when I run my specs I must wait 1 minute which is bad. How can I stub it? I was reading through many topics but I didn't find solution for that...

Upvotes: 2

Views: 3275

Answers (2)

John Donner
John Donner

Reputation: 542

As @Rubyrider mentioned, this link offers good help: RSpec: stubbing Kernel::sleep?

To sum up that answer, you can allow the class where sleep is called to receive the sleep method:

# Class that calls `sleep`
class Foo
  def run
    sleep 5
  end
end

# Specs
...
describe '#run' do
  before { allow_any_instance_of(Foo).to receive(:sleep) }

  # your tests
end

This will mock the sleep method and prevent it from being run during these tests.

While you could also check for Rails.env.test? in your code where you call sleep as @MilesStanfield suggested, I always try to stay clear of having code related to my tests in my regular code.

Upvotes: 3

MilesStanfield
MilesStanfield

Reputation: 4649

If it were me, i would just add a Rails.env.test? so your tests don't run the sleep call. Like this ...

until panel_import.completed?
  panel_import.update_status
  sleep 1.minute unless Rails.env.test?
end

Upvotes: 1

Related Questions