【问题标题】:Mock or Stub DateTime in Minitest rubyMinitest ruby​​ 中的模拟或存根日期时间
【发布时间】:2015-03-03 17:05:30
【问题描述】:

我在 User 模型上实现了 last_active_at 属性,每次用户访问网站上的页面时都会更新该属性。

当尝试在日期时间上使用模拟测试此属性的设置时,我得到一个NoMethodError: undefined method 'expect' for DateTime:Class

这是我在文件 chapter_controller_test.rb 中的测试:

test "save user last activity timestamp" do
  user = FactoryGirl.create(:user, student_type: User::REMOTE)
  session[:user_id] = user.id
  some_date = DateTime.new(2014, 12, 12, 1, 1, 1)
  DateTime.expect(:now, some_date)
  get :index
  assert_equal(some_date, user.last_active_at)
end

以及 ApplicationController 中的实现:

before_filter :record_activity

def record_activity
  if current_user && current_user.remote?
    current_user.last_active_at = DateTime.now
    current_user.save
  end
end

我正在使用 minitest 5.1

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby datetime mocking minitest


    【解决方案1】:

    恐怕你不能这样使用expect。试试这样的:

    test "save user last activity timestamp" do
      user = FactoryGirl.create(:user, student_type: User::REMOTE)
      session[:user_id] = user.id
      some_date = DateTime.new(2014, 12, 12, 1, 1, 1)
      DateTime.stub :now, some_date do
        get :index
        assert_equal(some_date, user.last_active_at)
      end
    end
    

    我目前无法自行检查,但请试一试!

    祝你好运!

    【讨论】:

    • 对于更复杂的时间/日期相关测试,timecop gem 非常棒github.com/travisjeffery/timecop
    • 同意!我试图在这里展示的是一种为 Minitest 存根/创建模拟的方法。使用DateTime 只是存根方法调用的一个示例。对于任何与时间相关的测试,timecop 是一种可行的方法 - 让我们说清楚!干杯!
    【解决方案2】:

    我终于设法通过安装 gem mocha 来存根(在这种情况下比模拟更有趣),我的测试现在看起来像这样:

    test "save user last activity timestamp" do
      user = FactoryGirl.create(:user, student_type: User::REMOTE)
      session[:user_id] = user.id
      some_date = DateTime.new(2014, 12, 12, 1, 1, 1)
      DateTime.stubs(:now).returns(some_date)
      get :index
      user.reload
      assert_equal(some_date, user.last_active_at)
    end
    

    对我来说很好。

    【讨论】:

      【解决方案3】:

      这是最小的,但对于 rails(你的情况),从 4.1 开始你可以使用travel_to

      travel_to Date.new(1986, 10, 25) do
        Date.current == Date.new(1985, 10, 25) # Marty! You've gotta come back with me!
      end
      

      【讨论】:

        猜你喜欢
        • 2017-02-14
        • 2012-05-14
        • 2018-06-06
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        • 2017-12-29
        相关资源
        最近更新 更多