ruby-on-rails - 如何允许在控制器中模拟本地范围的变量以接收消息?
问题描述
所以,我只做 Ruby 几天。任何提示将不胜感激。
变量.rb
class Variable < ApplicationRecord
def some_attribute=(value)
#do something with the vlue
end
end
X_Controller.rb
class XController < ApplicationController
def do_something
variable = Variable.instance_with_id(params[:id])
variable.some_attribute = some_new_value
redirect_to(some_url)
end
end
x_controller_spec.rb
describe '#do_something' do
before do
allow(Variable).to receive(:instance_with_id) # Works fine
allow_any_instance_of(Variable).to receive(:some_attribute)
post :do_something, :params => { id: 'uuid' }, :format => :json
end
it {
expect(variable).to have_received(:some_attribute)
}
end
解决方案
你可能想要这个:
let(:variable) { instance_double("Variable") }
before do
allow(Variable).to receive(:instance_with_id).and_return(variable)
allow(variable).to receive(:some_attribute=)
# ...
end
因为instance_with_id
应该返回一些东西。然后你想允许在那个实例上调用some_attribute=
(注意)。=
推荐阅读
- php - 如何在 XML 子标签中插入数据
- angular - 使用 httpclient 进行角度单元测试
- python - 如果使用了一个值,我如何输出一个值?
- google-places-api - 如何在 Blazor Web Assembly 中设置 Google Place 自动完成地址表单?
- c++ - 在 c++ 中使用 opencv 时如何加载 Pytorch 模型(.pt)
- php - 验证同一页面上的多个 html 表单
- r - 从列表中提取元素以创建数据框
- java - 执行处理器“org.thymeleaf.spring5.processor.SpringOptionFieldTagProcessor”时出错
- haskell - 使受约束的函数成为类型类实例
- docker - Docker:VueJS 无法解析服务名称后端