【发布时间】:2014-11-26 07:38:07
【问题描述】:
(这个问题类似于Ruby on Rails Method Mocks in the Controller,但使用的是旧的stub 语法,而且没有得到有效的答案。)
短格式
我想将我的控制器代码与我的模型代码分开测试。不应该是 rspec 代码:
expect(real_time_device).to receive(:sync_readings)
确认RealTimeDevice#sync_readings 被调用,但禁止实际调用?
详情
我的控制器有一个调用RealTimeDevice#sync_readings 的#refresh 方法:
# app/controllers/real_time_devices_controller.rb
class RealTimeDevicesController < ApplicationController
before_action :set_real_time_device, only: [:show, :refresh]
<snip>
def refresh
@real_time_device.sync_readings
redirect_to :back
end
<snip>
end
在我的控制器测试中,我想验证 (a) 正在设置 @real_time_device 并且 (b) #sync_reading 模型方法被调用(但我不想调用模型方法本身,因为那是模型单元测试涵盖)。
这是我的 controller_spec 代码不起作用:
# file: spec/controllers/real_time_devices_controller_spec.rb
require 'rails_helper'
<snip>
describe "PUT refresh" do
it "assigns the requested real_time_device as @real_time_device" do
real_time_device = RealTimeDevice.create! valid_attributes
expect(real_time_device).to receive(:sync_readings)
put :refresh, {:id => real_time_device.to_param}, valid_session
expect(assigns(:real_time_device)).to eq(real_time_device)
end
end
<snip>
当我运行测试时,实际的 RealTimeDevice#sync_readings 方法被调用,即它试图调用我模型中的代码。我想到了这条线:
expect(real_time_device).to receive(:sync_readings)
对于存根方法并验证它是否被调用是必要且足够的。我的怀疑是它需要是双重的。但我也看不到如何使用双精度编写测试。
我错过了什么?
【问题讨论】:
标签: ruby-on-rails unit-testing rspec controller