You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby控制器中mock局部作用域变量以使其可接收消息完成测试验证

解决方案

你不需要尝试获取控制器内部的局部变量,只需要提前把Variable.instance_with_id的返回值替换为你自己持有引用的测试对象即可,同时注意你之前的stub写错了方法名:你调用的是setter方法some_attribute=,不是gettersome_attribute。

修改后的测试代码如下:

describe '#do_something' do
  let(:test_variable) { Variable.new } # 也可以用double('Variable')做纯Mock

  before do
    # 指定instance_with_id返回我们提前创建的测试实例
    allow(Variable).to receive(:instance_with_id).with('uuid').and_return(test_variable)
    # stub对应的setter方法,注意方法名带等号
    allow(test_variable).to receive(:some_attribute=)
    
    post :do_something, :params => { id: 'uuid' }, :format => :json 
  end

  it 'should assign some_attribute to the variable' do 
    expect(test_variable).to have_received(:some_attribute=).with(some_new_value)
    # 如果你不知道some_new_value的具体值,也可以去掉with参数只验证方法调用
  end
end

改动说明

  • 用let提前创建测试用的Variable实例,你可以持有这个实例的引用直接做断言
  • 给instance_with_id的stub添加参数匹配和返回值,控制器里拿到的variable变量就是你创建的测试实例
  • 修正了stub的方法名,需要和实际调用的setter方法some_attribute=保持一致,否则收不到调用匹配

内容的提问来源于stack exchange,提问作者Karim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:27:04