ruby-on-rails - 如何监视 ActiveRecord 模型上在类级别调用的方法?
问题描述
如果我有模特
module MyModule
def bar(str)
puts str
end
end
MyModel < ActiveRecord::Base
include MyModule
bar('foo')
end
我的规格:
describe MyModel do
before do
described_class.stubs(:bar)
end
it 'calls bar with correct arguments' do
# This does not work because it is called before it gets stubbed
expect(described_class).to have_received(:bar).with('foo')
end
end
MyModule#bar
从 调用时我如何监视MyModel
?
使用 rspec-rails 2.99 和 mocha 0.13.3
解决方案
如果你在别处调用MyModel.new.bar,你可以在测试中写
expect_any_instance_of(MyModel).to receive(:bar)
如果你想使用'spy',你可以使用:
allow_any_instance_of(MyModel).to receive(:bar)
如果您在测试中有指向您的 MyModel 实例的链接,则可以这样重写上面的示例:
expect(my_model_instance).to receive(:bar)
或者
allow(my_model_instance).to receive(:bar)
您应该明白,在您的类中包含任何模块后,该类的实例将成为该方法的接收者。
推荐阅读
- python - 神经网络样本
- python - != 后面只能有一个字符串吗?
- react-native - React Native 组件未定义
- php - 如何在 Typo3 9 LTS 中添加自定义 PHP 文件
- c# - UserControl 中的 RoutedCommand 未按预期工作
- reactjs - 如何导航到从当前页面获取参数的下一页并即使在浏览器刷新后仍然保持反应
- angular - 当我在 ionic 中输入电子邮件时,我想从 firebase 获取用户 ID
- xslt - 如何从 XSLT 3.0 中的函数返回映射?
- .net - 如何在不从数据库中删除的情况下将 DataRow 从其集合中排除?
- python - 如何使用 melspectogram 将 wav 文件转换为 RGB 图像?