Mocking a method in RSpec

Mocking is used in testing, to isolate the behaviour of an object or a method. Usually when the dependent method or object is complex.

Let’ s take an example, a method to generate full name of a person.

class Person
  def full_name
    "#{first name} #{last_name}"
  end
end

The method full_name calls two other method first_name and last_name.

The complete code as below

class Person
  def full_name
    "#{first_name} #{last_name}"
  end
  
  def first_name
    # Get first name from the database
  end

  def last_name
    # Get last name from the database
  end
end

first_name and last_name methods do a database call to get the data.

But when you are testing the full_name method, you only need to see whether the full name is a combination of first name and last name

Here you really don’t need to worry what first_name and last_name methods does. So we can mock those methods.

The RSpec test can be written as follows by mocking first_name and last_name method

RSpec.describe Person do
  it "check the full name is combination of first name and last name" do
    allow(subject).to receive(:first_name).and_return("William") 
    allow(subject).to receive(:last_name).and_return("Dale")
    expect(subject.full_name).to eq("William Dale")
  end  
end

Leave a Reply

Your email address will not be published. Required fields are marked *