Ruslan Kornev
Posted on July 3, 2023
Hi, it's a super short and however helpful post about custom RSpec AR matcher. Do you like the conciseness of the code like me?
I like tests that use the simple is_expected
method. Take a look at the differences:
subject { 1 == 1 }
it { is_expected.to be_true }
instead of
expect(subject).to be_true
Maybe in this example, the problem is not so evident, but take a look at the following example:
Suppose we have validation on Post.title presence
subject { Post.new }
expect(subject.errors.of_kind?((:title, :presence))).to be_true
https://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-of_kind-3F
Looks weird? So it would be cool if we could make it more expressive, right, for example like this:
it { is_expected.to has_errors(:title, :presence) }
To do this way is super simple. Take a look at custom matchers: https://rspec.info/documentation/3.0/rspec-expectations/RSpec/Matchers
As a reference, you may copy code from my open-source project:
What do you think? May be I should even create gem with this feature? Or may be it's already exists and I don't hear about it?!
Posted on July 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.