【问题标题】:How to check block is called using rspec如何使用 rspec 调用检查块
【发布时间】:2017-11-19 18:04:32
【问题描述】:

我想检查是否使用 rspec 在我的函数中调用了该块。以下是我的代码:

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




describe SP do
 it "testing speak functionality can receive a block" do
    sp = SP.new
    def test_func 
        a = 1
    end
    sp_mock = double(sp)
    expect(sp_mock).to receive(:speak).with(test_func)
    sp.speak(test_func)
 end  
end 

以下是我的错误:

SP testing speak functionality can receive a block
     Failure/Error: block.call()

     NoMethodError:
       undefined method `call' for nil:NilClass
     # ./test.rb:9:in `speak'
     # ./test.rb:25:in `block (2 levels) in <top (required)>'

你能帮忙吗?我花了很多时间。

【问题讨论】:

    标签: ruby rspec ruby-block


    【解决方案1】:

    您必须使用 RSpec 的yield matcher 之一:

    describe SP do
      it "testing speak functionality can receive a block" do
        sp = SP.new
        expect { |b| sp.speak(&b) }.to yield_control
      end
    end
    

    【讨论】:

      【解决方案2】:

      我认为 Stefan 提供了最佳答案。不过我想指出的是,您应该测试代码的行为而不是实现细节。

      describe SP do
        it "testing speak functionality can receive a block" do
          sp = SP.new
          called = false
          test_func = -> () { called = true }
      
          sp.speak(&test_func)
      
          expect(called).to eql(true)
        end  
      end
      

      【讨论】:

      • yield_control 就是这样做的,不是吗?
      • @Stefan 这取决于您实际想要测试的内容。在这种情况下,.yield_with_no_args 将是最具体的测试。但是由于 SP#speak 的行为因传递的块而异,因此您也应该涵盖这些情况。在测试设置中,通过的块应该是raise ZeroDivisionError
      猜你喜欢
      • 2014-05-22
      • 2013-07-24
      • 2020-07-28
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2015-06-23
      • 2021-09-12
      • 1970-01-01
      相关资源
      最近更新 更多