【问题标题】:Pass a ruby &block using rspec使用 rspec 传递一个 ruby​​ &block
【发布时间】:2017-11-19 13:27:11
【问题描述】:

我想使用接收匿名块且不引发错误的 rspec 来测试该方法的功能。以下是我的代码:

class SP
  def speak(options={},&block)
    puts "speak called" 
    block.call()
  rescue StandardError => e
    puts e.inspect()
  end  
end


describe SP do
  it "testing speak functionality not to raise error" do
    sp = SP.new
    sp_mock = double(sp)
    expect(sp_mock).to receive(:speak).with(sp.speak{raise StandardError}).not_to raise_error
  end  
end 

下面是抛出错误

SP testing speak functionality not to raise error

 Failure/Error: expect(sp).to receive(:speak).with(sp.speak{raise StandardError})

   (#<SP:0x007fead2081d20>).speak(nil)
       expected: 1 time with arguments: (nil)
       received: 0 times
 # ./test.rb:22:in `block (2 levels) in <top (required)>'

花了很多时间浏览 ruby​​ 块和 ruby​​ 文档的文章,但无法弄清楚。

【问题讨论】:

  • 您无需在帖子中添加“已编辑”。这不是reddit。我们可以查看帖子编辑的完整历史记录。
  • 您的期望是 sp_mock 可以通过 speak 调用,但您没有在测试中调用 sp_mock.speak。

标签: ruby rspec ruby-block


【解决方案1】:

无缘无故太复杂了。你是这个意思吗?

it "testing speak functionality not to raise error" do
  sp = SP.new
  expect {
    sp.speak {raise StandardError}
  }.to_not raise_error
end  

【讨论】:

  • 是的,我可以这样做,但我的动机是使用 rspec 将块传递给函数
  • @OJASJUNEJA:你希望通过它完成什么?
  • @OJASJUNEJA 你不能通过 rspec 传递任何东西。 expect to receive 构造仅设置期望。您可以获取/调用传递给您的块。但实际调用必须由“常规红宝石”完成。
  • 其实这只是我真实工作的演示。我不能在这里发布它。我有将 &block 作为参数并在其定义中调用该块的函数。我知道如何编写 rspec 测试用例。我只是无法使用 rspec 将块传递给函数
  • 但是我们有 rspec receive(:method).with()... source:relishapp.com/rspec/rspec-mocks/v/3-2/docs/setting-constraints/…
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多