【问题标题】:Using RSpec to receive methods created on the fly for Ruby struct使用 RSpec 接收为 Ruby 结构动态创建的方法
【发布时间】:2015-07-15 15:05:29
【问题描述】:

我想知道如何使用 RSpec 来存根为 Ruby 结构动态创建的方法。

我的代码如下所示:

def test_method
  queue.poll do |message|
    puts message.body
  end
end

message 是一个结构体。方法 :body 当然不是内置在 Ruby 结构类中,而是作为外部库的一部分动态创建的。我想知道如何将呼叫存根到:body

我的 RSpec 测试如下所示:

let(:poller) { instance_double(ExternalLibrary::QueuePoller) }
let(:msg) { instance_double(Struct) }

before do
  allow(ExternalLibrary::QueuePoller).to receive(:new).and_return(poller)
  allow(poller).to receive(:poll).and_yield(msg)
end

it 'polls the queue' do
  allow(msg).to receive(:body)
  described_class.new.test_method
end

但我有以下错误:

  1) polls the queue
     Failure/Error: allow(msg).to receive(:body)
       Struct does not implement: body

如何正确运行测试?感谢您的帮助。

【问题讨论】:

    标签: ruby struct rspec


    【解决方案1】:

    您可以将哈希指定为instance_double 的第二个参数。所以而不是:

    let(:msg) { instance_double(Struct) }
    

    用途:

    let(:msg) { instance_double(Struct, body: '') }
    

    不确定您是否会将 Struct 放在引号中:

    let(:msg) { instance_double("Struct", body: '') }
    

    这一切都基于此链接: https://relishapp.com/rspec/rspec-mocks/docs/verifying-doubles/dynamic-classes 这似乎解决了同样的问题

    【讨论】:

    • 我尝试了你的方法,在 Struct 周围加引号和不加引号,但都不管用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2016-08-31
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多