What is RSpec eq eql and equal?

RSpec provides a number of useful matchers which allow you to compare expected results.

Let us understand what “eq”, “eql” and “equal” does exactly, so that you will no more in confusion which one to choose when writing tests

The eq matcher

The “eq” matcher compares the value of two objects.

Using eq matcher will pass all following 3 tests

RSpec.describe "the eq matcher" do
  a = 10.0
  b = 10
  it "shows eq pass for same values" do
    expect(a).to eq(b) 
  end
end
RSpec.describe "the eq matcher" do
  a = "john"
  b = "john"
  it "shows eq pass for same values" do
    expect(a).to eq(b)
  end
end
RSpec.describe "the eq matcher" do
  a = "john"
  b = a
  it "shows eq pass for same values" do
    expect(a).to eq(b)
  end
end

The eql matcher

The eql matcher not only check for the values but also for the type of the object

Using eql matcher fails first test, but remaining two will pass

RSpec.describe "the eql matcher" do
  a = 10.0
  b = 10
  it "shows eql fails if the type of objects are not same" do
    expect(a).to eql(b) 
  end
end
RSpec.describe "the eql matcher" do
  a = "john"
  b = "john"
  it "shows eql pass for same value and type" do
    expect(a).to eql(b)
  end
end
RSpec.describe "the eql matcher" do
  a = "john"
  b = a
  it "shows eql pass for same value and type" do
    expect(a).to eql(b)
  end
end

The equal matcher

The equal matcher not just check for the value and type, but check for the object identity, checks whether both are the same object itself.

Using equal fails first two tests, only the last one will pass

RSpec.describe "the equal matcher" do
  a = 10.0
  b = 10
  it "shows equal fails if the type of objects are not same" do
    expect(a).to equal(b)
  end
end
RSpec.describe "the equal matcher" do
  a = "john"
  b = "john"
  it "shows equal fails if the objects are not same" do
    expect(a).to equal(b)
  end
end
RSpec.describe "the equal matcher" do
  a = "john"
  b = a
  it "shows equal pass for same if the objects are same" do
    expect(a).to equal(b)
  end
end

The eq – eql – equal comparison table

Let me put above details into a simple comparison table, something we can refer easily when needed

RSpec eq eql equal comparison

Leave a Reply

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