rubyrspec

What is this notation in rspec: it { is_expected.to ... }


I am reading the 'Better specs' page, and in one of the examples it says:

context 'when logged in' do
  it { is_expected.to respond_with 200 }
end
context 'when logged out' do
  it { is_expected.to respond_with 401 }
end

And I don't recognize this. I usually would do:

context 'when logged out' do
  it 'responds with a 401' do
    expect(response).to eq(401)
  end
end

What is that syntax?


Solution

  • This is something introduced heavily in Rspec 3.XX. It's under the one line syntax guides as outlined here

    RSpec supports a one-liner syntax for setting an expectation on the subject. RSpec will give the examples a doc string that is auto- generated from the matcher used in the example. This is designed specifically to help avoid duplication in situations where the doc string and the matcher used in the example mirror each other exactly. When used excessively, it can produce documentation output that does not read well or contribute to understanding the object you are describing.

    This comes in two flavors:

    is_expected is defined simply as expect(subject) and is designed for when you are using rspec-expectations with its newer expect-based syntax.