Wednesday, 15 July 2015

Rails RSpec Mocking Date.today.wday in Rake Task -



Rails RSpec Mocking Date.today.wday in Rake Task -

i'm trying mock date.today.wday in rake task in rspec.

gem versions: rspec 2.14.8 --- rails 4.1.1 --- ruby 2.0.0

here simplified false version of test illustrate i'm trying do:

describe "scheduler" describe ":thursday_invitations" let(:run_issue_invites) rake::task[:thursday_invitations].reenable rake.application.invoke_task :thursday_invitations end before rake.application.rake_require 'tasks/scheduler' rake::task.define_task(:environment) date.today.should_receive(:wday).and_return(4) ###my nemesis code line end context "on thursday" "issues invitations" expect(date.today.wday).to eq(4) ###the verification test keeps failing run_issue_invites expect(<other_stuff_to_test>).to <return_properly> end end end end

so, real key of mocking out date.today.wday. because want able run spec on day of week, need mock/stub out method homecoming "4" (the day-number th in rails). so, setup test first verify receiving "4" (the assertion in test). if today is, say, fri (which is) , run test, fails saying expected "4" got "5". is, not returning value want when receive method. have tried stubbing similar ineffective results. normally, mocking breeze, seems hangup .wday operates on date.today.

because rake task (which i'm not familiar mocking), may have specify further, haven't been able bottom of it...

let me know if need other clarifying information.

i believe reason you're not seeing behavior expect object mocking not same object under test.

in rails 4+ environment, see on rails console:

[1]> date.today.object_id 70104549170200 [2]> date.today.object_id 70104552970360

the fact object_id different in subsequent calls date.today means each phone call returns new object. date.today.should_receive(:wday).and_return(4) setting expectation on object never used again.

you'll need rewrite spec ensure same object returned date.today each time. here's 1 solution, omitting other parts of illustration clarity:

let!(:today) { date.today } before date.stub(:today).and_return(today) today.should_receive(:wday).and_return(4) end "issues invitations" expect(date.today.wday).to eq(4) end

ruby-on-rails rspec rake

No comments:

Post a Comment