首页 > 解决方案 > 如何监视 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

标签: ruby-on-railsrubyrspec

解决方案


如果你在别处调用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)

您应该明白,在您的类中包含任何模块后,该类的实例将成为该方法的接收者。


推荐阅读