Minitest ruby中的Mock或Stub DateTime

wz3gfoph  于 2023-08-04  发布在  Ruby
关注(0)|答案(3)|浏览(101)

我在User模型上实现了一个last_active_at属性,它将在用户每次访问网站上的页面时更新。
当尝试在datetime上使用mock测试此属性的设置时,我得到了一个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


我用的是迷你测试5.1

k5hmc34c

k5hmc34c1#

这是minitest,但对于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

字符串

bbuxkriu

bbuxkriu2#

恐怕你不能这样使用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

字符串
我现在不能自己检查,但给予看!
祝你好运!

k75qkfdt

k75qkfdt3#

最后,我通过安装gem mocha来实现stub(在这种情况下比mock更有趣),我的测试现在看起来像这样:

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

字符串
对我来说很好。

相关问题