Time.nowã®ãã¹ãï¼ ããMochaã§ã§ããã
[ruby][rails]テストの時にTime.nowで好きな時間を使えるようにするMock - よしだメモ
Time.nowã¯å½è£
ããªãã¨ãã¹ãã¯æ¸ããªãã
ã ã£ãããããªã¾ãããã©ããã¨ããªãã§Mocha使ããããstubã§ç°¡åã«å½è£
ã§ããããã
Mochaã®å½è£
ã®ã¹ã³ã¼ãã¯ãã¹ãã¡ã½ãããçµããã¾ã§ããã¹ãã¡ã½ãããçµãã£ããåæã«å½è£
ã®å¾çä»ãããã¦ãããã
ãã¹ããããªãã°ã¢ãã¯ã¨ã¹ã¿ãã¯æ¯é身ã«ä»ãããã¨ããã
ã¡ãªã¿ã«1993/2/24ã¯Rubyã®èªçæ¥ã ã
def current_date Time.now.strftime "%Y/%m/%d" end require 'test/unit' require 'rubygems' require 'mocha' class TestTimeNow < Test::Unit::TestCase def test_current_date Time.stubs(:now).returns(Time.local(1993,2,24)) assert_equal "1993/02/24", current_date end end # >> Loaded suite - # >> Started # >> . # >> Finished in 0.007321158 seconds. # >> # >> 1 tests, 1 assertions, 0 failures, 0 errors
expectationsã¯Mochaçµã¿è¾¼ã¿ãªã®ã§ãã£ããæ¸ããã
require 'rubygems' require 'expectations' Expectations do expect "1993/02/24" do Time.stubs(:now).returns(Time.local(1993,2,24)) current_date end end # >> Expectations . # >> Finished in 0.001 seconds # >> # >> Success: 1 fulfilled
追è¨
ãããããããã¦ãã£ãï¼ry
require 'test/unit' require 'rubygems' require 'mocha' class TestDio < Test::Unit::TestCase def test_the_world now = Time.now # ã¶ã»ã¯ã¼ã«ãï¼æãæ¢ã¾ã Time.stubs(:now).returns(now) sleep 2 assert_equal now, Time.now end def teardown # ããã¦æã¯åãã ã end end # >> Loaded suite - # >> Started # >> . # >> Finished in 1.999748 seconds. # >> # >> 1 tests, 1 assertions, 0 failures, 0 errors