如何在不使用sleep(1.second)方法的情况下编写规范?当我删除睡眠时,我的测试会因为返回相同的时间戳而中断?
我有以下类方法:
def skip
qs = find_or_create_by(user_id: user_id)
qs.set_updated_at
qs.n_skip += 1
qs.save!
end
并遵循规范:
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
答案 0 :(得分:9)
我过去曾使用Timecop gem进行基于时间的测试。
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
所以你的例子可能如下:
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
答案 1 :(得分:1)
这也适用于rspec测试。在您的Gemfile中:
require 'timecop', group: :test
然后,例如,您可以使用rspec来测试命名范围,该范围以降序的updated_at顺序获取名为查询的模型:
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