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}"

require 'rails_helper'

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

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

  include Personable

Top comments (1)

melashu profile image

You save my day thanks!