How to implement have_many/belong_to RSpec matchers

You’re going to writing test for you’re ActiveRecord models to check if they have a specific set of associations?!

You have two options; going with shoulda-matchers gem (that’s a great gem, though) or writing a simple version of yourself for learning or reduce complexity of using too many gems.

At first you should create a file under spec/support/ called association.rb (call it whatever you want) then require it in your test helper (whether it’s spec_helper or rails_helper)

require_relative "support/association"

And all you have to do is


Here we have defined two matchers have_many and belong_to using ActiveRecord::Reflection#reflect_on_association which allows us to get a AssociationReflection object to check whether an association with a specific named is declared or not. Actually to avoid complexity I’ve skipped error handling part which you can steal from shoulda-matchers gem to be more concise.

And now you can write test cases like this:


That’s it, hope you’ve enjoyed. It’s good to go under the hood and get dirty to see how Ruby/Ruby On Rails magic works.

∞ Travel | Coding | Lifestyle ⦿ Bangkok | ✧ #freelancer ▷ Got a project? ⭣

∞ Travel | Coding | Lifestyle ⦿ Bangkok | ✧ #freelancer ▷ Got a project? ⭣