How would I rspec / check the updated_at field without using the sleep () function in ruby?

How to write my spec without using the sleep (1.second) method? When I delete a dream, my tests are interrupted because they return the same timestamp?

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 the following specification:

  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 
+6
source share
2 answers

I used the Timecop gem in the past to conduct 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 might look like this:

 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 
+9
source

This also works well for rspec tests. In your gemfile:

 require 'timecop', group: :test 

Then, for example, you can use rspec to check the named area that receives the model called queries in descending order of update_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 
+1
source

Source: https://habr.com/ru/post/927793/


All Articles