Conveying Intent with RSpec subject
Today during a test refactor, I discovered RSpec's subject
method. We used it a lot, because it helps convey the test's intent.
subject
can be used as a convenience method, and to define the intent of a test. If you've ever seen a comment # This is what we are testing
, subject
would be an upgrade to that.
Here are three passing examples of this method in practice, from most to least verbose.
Explicit, with a named subject:
RSpec.describe Array, "with some elements, explicit named subject" do
subject(:array) { [1, 2, 3] }
it "should have the prescribed elements" do
expect(array).to eq [1, 2, 3]
end
end
Explicit, with no name:
RSpec.describe Array, "with some elements, explicit subject" do
subject { [1, 2, 3] }
it "should have the prescribed elements" do
expect(subject).to eq [1, 2, 3]
end
end
Implicit:
RSpec.describe Array, "with some elements, implicit subject" do
it "should have the default elements" do
expect(subject).to be_empty
end
end
Substitute this for let
on your described class. There are a ton of interesting uses and edges for this method, so dig into those docs.
h/t Mike Chau
Tweet