RSpect : need to be taken care of while writing UnitTesting

Ok let me show an example

let(:role) { create :role, name: 'parent' }
let(:user) { create(:user1, roles: [role]) }
let(:pact) { create :pact, parent_id: user.id, renews_at: 1.hour.ago }
let(:execution){ AutoRenewalPactAsync.new.perform}

it 'should renew pact and also schedule the drug test whose renews_at date is today' do
  expect{execution}.to change{pact.pact_years.count}.by(1)
  expect(pact.renews_at).to eq(pact.renews_at + Pact::RenewalYear)
end
------------------------------------------------------------------
Failure/Error: expect(pact.renews_at).to eq(1.year.from_now)
 
 expected: 2017-02-28 09:20:41.204897017 +0000
 got: 2016-02-28 08:20:40.980794147 +0000

Did you notice what went wrong?. Well what I was doing wrong was, I was expecting the value of stale object to be updated by the execution.

Correction:

it 'should renew pact and also schedule the drug test whose renews_at date is today' do
  expect{execution}.to change{pact.pact_years.count}.by(1)

  updated_pact = Pact.find(pact.id)
  expect(updated_pact.renews_at).to eq(pact.renews_at + Pact::RenewalYear)
end
------------------------------------------------------------------
Failure/Error: expect(updated_pact.renews_at).to eq(pact.renews_at + Pact::RenewalYear)
 
 expected: 2017-02-28 08:27:50.125348477 +0000
 got: 2017-02-28 08:27:50.125348000 +0000

This time the issue was: I was comparing the DateTime object and for them to be equal, even the milli/micro seconds have to be equal.

Correction:

updated_pact = Pact.find(pact.id)
expect(updated_pact.renews_at.to_date).to eq(pact.renews_at.to_date + Pact::RenewalYear)
should renew pact and also schedule the drug test whose renews_at date is today
Finished in 5.76 seconds (files took 5.35 seconds to load)
4 examples, 0 failures, 2 pending

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s