JayTarka
JayTarka

Reputation: 571

Can I use is_expected with block matchers?

The raise_error is a matcher that supports block expectations.

Below I have a spec testing that the foo method raises an error:

require 'rspec'
def foo
   raise StandardError
end

describe 'foo' do
    subject{ foo }
    specify{ expect{ subject }.to raise_error }
    it{ is_expected.to raise_error }
end

Now, specify{ expect{ foo }.to raise_error } passes as expected, but it{ is_expected.to raise_error } fails. It fails because StandardError is raised and is not rescued by the raise_error matcher.

So can I use blocks with is_expected? Or am I destined to write specify{ expect{ subject } over and over and over again? Will rspec be supporting blocks for use with is_expected in the future?

Upvotes: 3

Views: 3013

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29399

Per the documentation, is_expected is simply equivalent to expect(subject). The StandardError you are getting is being raised by the evaluation of the subject parameter to is_expected. The matcher is never invoked.

It doesn't make sense for is_expected to take a block, since its purpose to implicitly operate on subject. However, if subject is defined to be a Proc or Lambda, then it does just what you'd expect it to do, as in the following:

describe 'foo' do
  subject{ Proc.new { foo } }
  specify{ expect{ subject.call }.to raise_error }
  it{ is_expected.to raise_error }
end

Upvotes: 3

Related Questions