6

如何在不使用 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
4

2 回答 2

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
于 2012-10-15T22:57:17.037 回答
2

这也适用于 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
于 2013-07-28T23:11:57.257 回答