DEV Community

YC Yap
YC Yap

Posted on

Testing concerns in rails

Rails's ActiveSupport::Concern can be a useful place to put code that needs to be shared across classes. It is also a way to implement multiple inheritance.

When it comes to testing a concern, we want to be testing the behaviour instead of the class which implements the concern, as it can be shared among multiple classes.

One of my preferred way to test a concern is to use a dummy class which inherits from ActiveRecord,it gives me confidence that i am testing against my actual ActiveRecord models.

module Personable
  extend ActiveSupport::Concern

  def full_name
    "#{first_name} #{last_name}"
  end
end

require 'rails_helper'

RSpec.describe Personable do
  it 'has a full name' do
    person = DummyPerson.new(first_name: 'yc', last_name: 'yap')
    expect(person.full_name).to eq 'yc yap'
  end
end

class DummyPerson < ActiveRecord::Base
  self.table_name = 'users'

  include Personable
end

Top comments (1)

Collapse
 
melashu profile image
Meshu

You save my day thanks!