断言 Redis 发布
Assert Redis publication
我正在为 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
我知道回调运行是因为我在最后打印 'published',并且我已经验证 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)>'
我正在使用 bourne 和 mocha 来使用 have_received
匹配器。
我怎样才能通过这个测试?
您可以尝试使用 expect_any_instance_of
模拟。
it 'broadcasts creation' do
expect(Redis.any_instance).to receive(:publish).twice
message = Message.create(body: 'foo')
end
https://www.relishapp.com/rspec/rspec-mocks/v/3-2/docs/working-with-legacy-code/any-instance
为 Redis
创建一个 mock 并分别剔除 class 和实例方法 — 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
我正在为 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
我知道回调运行是因为我在最后打印 'published',并且我已经验证 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)>'
我正在使用 bourne 和 mocha 来使用 have_received
匹配器。
我怎样才能通过这个测试?
您可以尝试使用 expect_any_instance_of
模拟。
it 'broadcasts creation' do
expect(Redis.any_instance).to receive(:publish).twice
message = Message.create(body: 'foo')
end
https://www.relishapp.com/rspec/rspec-mocks/v/3-2/docs/working-with-legacy-code/any-instance
为 Redis
创建一个 mock 并分别剔除 class 和实例方法 — 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