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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay