How do i write my spec without using the sleep(1.second) method? When I remove the sleep then my tests break because they are returning the same time stamp?
I have the following class method:
def skip
qs = find_or_create_by(user_id: user_id)
qs.set_updated_at
qs.n_skip += 1
qs.save!
end
and following spec:
qs = skip(user.id)
sleep(1.second)
qs2 = skip(user.id)
qs.should_not be_nil
qs2.should_not be_nil
(qs.updated_at < qs2.updated_at).should be_true
I've used the Timecop gem in the past for doing time based testing.
require 'timecop'
require 'test/unit'
class MyTestCase < Test::Unit::TestCase
def test_mortgage_due_in_30_days
john = User.find(1)
john.sign_mortgage!
assert !john.mortgage_payment_due?
Timecop.travel(Time.now + 30.days) do
assert john.mortgage_payment_due?
end
end
end
So your example may look like:
qs = skip(user.id)
Timecop.travel(Time.now + 1.minute) do
qs2 = skip(user.id)
end
qs.should_not be_nil
qs2.should_not be_nil
(qs.updated_at < qs2.updated_at).should be_true
This also works well for rspec tests. In your Gemfile:
require 'timecop', group: :test
Then, for example, you can use rspec to test a named scope that gets model called queries in descending updated_at order:
require 'timecop'
require 'spec_helper'
describe Query do
# test the named scopes for ordering and searching
describe 'when a query is searched or sorted' do
before :each do
@query1 = create(:query)
Timecop.travel(Time.now + 1.minute) do
@query2 = create(:query)
end
Timecop.travel(Time.now + 2.minute) do
@query3 = create(:query)
end
end
it 'should be listed in descending updated_at order' do
@queries = Query.order_by_latest
@queries.first.should == @query3
@queries.last.should == @query1
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With