Rspec: expect vs expect with block - what's the difference?

旧街凉风 提交于 2019-11-27 07:48:02

As has been mentioned:

expect(4).to eq(4)

This is specifically testing the value that you've sent in as the parameter to the method. When you're trying to test for raised errors when you do the same thing:

expect(raise "fail!").to raise_error

Your argument is evaluated immediately and that exception will be thrown and your test will blow up right there.

However, when you use a block (and this is basic ruby), the block contents isn't executed immediately - it's execution is determined by the method you're calling (in this case, the expect method handles when to execute your block):

expect{raise "fail!"}.to raise_error

We can look at an example method that might handle this behavior:

def expect(val=nil)
  if block_given?
    begin
      yield
    rescue
      puts "Your block raised an error!"
    end
  else
    puts "The value under test is #{val}"
  end
end

You can see here that it's the expect method that is manually rescuing your error so that it can test whether or not errors are raised, etc. yield is a ruby method's way of executing whatever block was passed to the method.

In the first case, when you pass a block to expect, the execution of the block doesn't occur until it's time to evaluate the result, at which point the RSpec code can catch any error that are raised and check it against the expectation.

In the second case, the error is raised when the argument to expect is evaluated, so the expect code has no chance to get involved.

As for rules, you pass a block or a Proc if you're trying to test behavior (e.g. raising errors, changing some value). Otherwise, you pass a "conventional" argument, in which case the value of that argument is what is tested.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!