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?
The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.
let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called. Here is an example of how let is used within an RSpec test. let will generate a method called thing which returns a new instance of Thing .
According to the rspec source code, “context” is just a alias method of “describe”, meaning that there is no functional difference between these two methods. However, there is a contextual difference that'll help to make your tests more understandable by using both of them.
RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.
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.
it { is_expected.to respond_with 200 }
that is more readable. Why you added description if you can read it from test. Your code should be simple, smart and readable in the same time... but if you realy want, you can add even novel... up to you :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With