DEV Community

Ruslan Kornev
Ruslan Kornev

Posted on

is_expected RSpec ActiveRecord matcher

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 }
Enter fullscreen mode Exit fullscreen mode
it { is_expected.to be_true }
Enter fullscreen mode Exit fullscreen mode

instead of

expect(subject).to be_true
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode
expect(subject.errors.of_kind?((:title, :presence))).to be_true
Enter fullscreen mode Exit fullscreen mode

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) }
Enter fullscreen mode Exit fullscreen mode

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:

https://github.com/woto/hub/commit/c45db2b33e85cec3fbbb69dfb3fac23a53d28051#diff-426a7f720d57b5501d595e6b1be7cb844598ebe8a4b584d32f1268b6056f3d2bR57

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?!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay