我正在为after_create回调编写规范。规格如下:
it 'broadcasts creation' do
message = Message.create(body: 'foo')
expect(Redis.any_instance).to have_received(:publish)
end我的Message模型如下所示:
class Message < ActiveRecord::Base
after_create -> { publish(:create) }
private
def publish(name)
Redis.new.publish(
self.class.inferred_channel_name,
json(action)
)
Redis.new.publish(
inferred_channel_name_for_single_record,
json(action)
)
puts 'published!'
end
end我知道回调运行是因为我在最后打印“已发布”,而且我已经证实Redis确实发布了两次。
尽管如此,我的规范在以下消息中还是失败了:
1) Message Methods #entangle without options broadcasts creation
Failure/Error: expect(Redis.any_instance).to have_received(:publish)
unstubbed, expected exactly once, not yet invoked: #<AnyInstance:Redis>.publish(any_parameters)
# ./spec/models/message_spec.rb:20:in `block (5 levels) in <top (required)>'我使用伯恩和摩卡使用have_received匹配器。
我怎样才能通过这个考试?
发布于 2015-02-22 23:28:13
为Redis创建一个模拟,并将类和实例方法分别存根出来-- new和publish。
it "broadcasts creation" do
redis = stub_redis
Message.create(body: "foo")
expect(redis).to have_received(:publish).twice
end
def stub_redis
mock("redis").tap do |redis|
redis.stubs(:publish)
Redis.stubs(:new).returns(redis)
end
end发布于 2015-02-22 22:32:09
您可以尝试使用expect_any_instance_of模拟。
it 'broadcasts creation' do
expect(Redis.any_instance).to receive(:publish).twice
message = Message.create(body: 'foo')
endhttps://www.relishapp.com/rspec/rspec-mocks/v/3-2/docs/working-with-legacy-code/any-instance
https://stackoverflow.com/questions/28663685
复制相似问题