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

Top comments (0)