日曜ITエンジニア劇場

日曜に勉強した情報の整理と、挑戦する新たな技術(私にとって)のつまづきポイントを綴っていきます。

RSpec/マッチャー(matchers)/等価


参考資料

公式サイト

relishapp.com


等価マッチャー使用例

require 'rails_helper'

RSpec.describe '等価matchers' do
  let(:string1) { 'kuro-neko' }
  let(:string2) { string1 }
  let(:integer1) { 3 }
  let(:integer2) { 3.0 }

  describe 'eqを使用' do
    context '内容が同一の文字列の場合' do
      it { expect(string1).to eq(string2) }
    end

    context '内容が異なる文字列の場合' do
      let(:string2) {'shiro-neko'}
      it { expect(string1).not_to eq(string2) }
    end

    context '同一の数値の場合' do
      it { expect(integer1).to eq(integer2) }
    end
  end

  describe '他に...' do
    describe '==を使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to be == string2 }
      end
    end

    describe 'eqlを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to eql(string2) }
      end
    end

    describe 'equalを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to equal(string2) }
      end
    end

    describe 'beを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to be(string2) }
      end
    end
  end
end

実行結果

$ bundle exec rspec spec/sample/matcher_spec.rb

等価matchers
  eqを使用
    内容が同一の文字列の場合
      is expected to eq "kuro-neko"
    内容が異なる文字列の場合
      is expected not to eq "shiro-neko"
    同一の数値の場合
      is expected to eq 3.0
  他に...
    ==を使用
      内容が同一の文字列の場合
        is expected to be == kuro-neko
    eqlを使用
      内容が同一の文字列の場合
        is expected to eql "kuro-neko"
    equalを使用
      内容が同一の文字列の場合
        is expected to equal "kuro-neko"
    beを使用
      内容が同一の文字列の場合
        is expected to equal "kuro-neko"

Finished in 0.0206 seconds (files took 1.26 seconds to load)
7 examples, 0 failures