RSpec predicate matchers
Rspec has a pretty handy feature called predicate matchers to test predicate methods on your classes.
Assume we have a method registered?
on our User
class:
class User
...
def registered?
profile.present?
end
...
end
And we have a usual spec:
describe '#registered?' do
it 'returns true when profile is present' do
profile = create(:user_with_profile) # using factory_girl
expect(profile.registered?).to eq(true)
end
it 'returns true when profile is absent' do
profile = create(:user)
expect(profile.registered?).to eq(false)
end
end
RSpec provides predicate matchers
which are dynamic matchers for your predicate methods (ones ending with a ?
).
Using this combined with the one-line matchers,
we can convert our specs to more readable ones:
describe '#registered?' do
context 'when profile is present' do
subject { create(:user_with_profile) }
it { is_expected.to be_registered }
end
context 'when profile is absent' do
subject { create(:user) }
it { is_expected.not_to be_registered }
end
end