RSpec is_anticipated helper

Josua Schmid
2 min readMar 30, 2020

This is about a little helper method called is_anticipated which complements is_expected — a trial to make RSpec even nicer.

Photo by Jonathan Borba on Unsplash

RSpec is a testing framework for Ruby. It has a long history and it’s incredibly powerful. For tests which have a lot of context switches you may use the one-liner syntax. So you may write concise tests like these:

describe '#apply' do
subject { described_class.new(params).apply(products) }

let(:products) { Product.all }

context 'when not filtering' do
before do
create(:product, name_de: 'A')
create(:product, name_de: 'B')
create(:product, name_de: 'C')
end

let(:params) { {} }

it { is_expected.to match_array(products) }
end

context 'when filtering via options (type 2, 7)' do
before { … }

let(:params) { { … } }

it { is_expected.to find_products('B', 'C') }
end
end

This may need a bit of practice to get used to, mainly because you may not immediately see the “act”-part of the test — it’s nested in the subject.

The problem

Now there’s a problem with the one-liner syntax, as stated in the docs:

The one-liner syntax only works with non-block expectations

This means you could not write a test like this (using db-query-matchers gem):

describe '#apply' do
subject { described_class.new(params).apply(products) }
it { is_expected.not_to make_database_queries }
end

It would raise an error like this:

Failure/Error: it { is_expected.not_to make_database_queries }TypeError:
wrong argument type (expected Proc)

The solution

I often introduce my little helper method is_anticipated into projects. The very simple setup looks like this:

# spec/support/is_anticipated.rb
module IsAnticipated
def is_anticipated
expect { subject }
end
end
# spec/rails_helper.rb
RSpec.configure do |config|
config.include IsAnticipated
end

With that in place the following test works like a charm:

describe '#apply' do
subject { described_class.new(params).apply(products) }
it { is_anticipated.not_to make_database_queries }
end

Why is_anticipated ?

Because “anticipate” means to expect something and take action in expectation while “expect” means regard as likely to happen and does not require any action.

[source]

--

--