Today I Learned

A Hashrocket project

Reflect on Association

Integration tests should expose flaws in our Rails domain models and associations pretty well. Any remaining uncertainty can be remedied by familiarity with the methods (has_many, belongs_to), entity relationship diagrams, and good old trial and error.

But what if we want to explicitly check our associations in a unit test?

Here’s one way, with reflect_on_association:

# app/models/hike.rb
class Hike < ActiveRecord::Base
  has_many :trips
end
# spec/models/hike_spec.rb
RSpec.describe Hike, type: :model do
  describe 'associations' do
    it 'has many trips' do
      ar = described_class.reflect_on_association(:trips)
      expect(ar.macro) == :has_many
    end
  end
end

Overkill? Probably. But it’s nice to have.

Source code:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/reflection.rb#L109

Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket and we'd love to take a look at your project. Contact us and find out how we can help you.