Yi Wen
2012-Jan-26 15:44 UTC
[rspec-users] What is the pattern for testing a time argument using argument matcher
Say I do: ```ruby object.method 5.days.ago ``` In the test I want to test using should_receive like: ```ruby object.should_receive(:method).with(5.days.ago) ``` This will fail since two time objects aren''t exact the same. What is the general pattern for testing this in rspec? Thanks
Morten Møller Riis
2012-Jan-26 15:54 UTC
[rspec-users] What is the pattern for testing a time argument using argument matcher
You can use things like Timecop. I prefer to just stub Time.now: timestamp = Time.now.to_i Time.stub(:now).returns(Time.at(timestamp)) Best regards Morten M?ller Riis On Jan 26, 2012, at 4:44 PM, Yi Wen wrote:> Say I do: > > ```ruby > object.method 5.days.ago > ``` > > In the test I want to test using should_receive like: > > ```ruby > object.should_receive(:method).with(5.days.ago) > ``` > > This will fail since two time objects aren''t exact the same. > > What is the general pattern for testing this in rspec? > > Thanks > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users-------------- next part -------------- An HTML attachment was scrubbed... URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20120126/19f3900f/attachment.html>
Justin Ko
2012-Jan-26 16:04 UTC
[rspec-users] What is the pattern for testing a time argument using argument matcher
On Jan 26, 2012, at 8:44 AM, Yi Wen wrote:> Say I do: > > ```ruby > object.method 5.days.ago > ``` > > In the test I want to test using should_receive like: > > ```ruby > object.should_receive(:method).with(5.days.ago) > ``` > > This will fail since two time objects aren''t exact the same. > > What is the general pattern for testing this in rspec? > > Thanks > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-usersIn general, it''s a good idea not to "hard code" time within the code that uses it. There are many ways to avoid doing this: 1.) Pass in the time. def method_that_uses_time(time) do_something_with_time(time) end it ''...'' do time = double(''time'') object.should_receive(:do_something_with_time).with(time) object.method_that_uses_time(time) end 2.) Put the time in it''s own method, and stub it. def method_that_uses_time do_something_with_time(the_time) end def the_time; 5.days.ago end it ''...'' do time = double(''time'') object.should_receive(:the_time).and_return(time) object.method_that_uses_time end And then there are gems like delorean and timecop, which "freeze" time.