首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >断言Redis出版物

断言Redis出版物
EN

Stack Overflow用户
提问于 2015-02-22 21:47:22
回答 2查看 386关注 0票数 0

我正在为after_create回调编写规范。规格如下:

代码语言:javascript
复制
it 'broadcasts creation' do
  message = Message.create(body: 'foo')
  expect(Redis.any_instance).to have_received(:publish)
end

我的Message模型如下所示:

代码语言:javascript
复制
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确实发布了两次。

尽管如此,我的规范在以下消息中还是失败了:

代码语言:javascript
复制
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匹配器。

我怎样才能通过这个考试?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-22 23:28:13

Redis创建一个模拟,并将类和实例方法分别存根出来-- newpublish

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2015-02-22 22:32:09

您可以尝试使用expect_any_instance_of模拟。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28663685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档