RSpecで役に立ちそうないくつかのヒント(翻訳)|TechRacho by BPS株式会社

hash_including

hash_includingマッチャは、ハッシュ全体を指定せずに、特定のキーバリューペアのアサーションを書くのに使えます。

サンプルコードは下記。

describe Book do
  describe '#fetch_information' do
    let(:book_genre) { '歴史創作もの' }
    let(:book_title) { '二都物語' }
    subject { Book.new(title, genre) }

    it 'クライアントが正常にインスタンス化される' do
      expect(HTTPClient).to receive(:new)
                        .with(hash_including(title: book_title, genre: book_genre))
      subject.fetch_information
    end
  end
end

キー名だけの指定も可能。

.with(hash_including(:title, :genre))

anything

anythingマッチャは「メソッドで引数が1個必要だが、引数は何であってもよい」テストを書くのに使えます。

context '本を複数渡した場合' do
  subject { Author.new(name, books) }
  let(:books) { [Book.new(anything, anything)] } #👈
  it 'trueになる' do
    expect(subject.has_written_a_book?).to eq(true)
  end
end

match_array

RubyのArray同士の比較は、両者の要素が完全に同一、かつ順序も一致する場合にのみ等しくなります。しかしテストによってはそこまで厳密な一致条件は不要な場合もあります。そんなときには、RSpecのmatch_arrayマッチャでテストをいい感じに書けます。

describe '#fetch_books' do
  let(:name) { 'ジェーン・オースティン' }
  let!(:books) do
    Array.new(2) do
      BookDB.create_book(author_name: name)
    end
  end

  subject { Author.new(name: name) }

  it '本のリストを正しく取り出せる' do
    expect(subject.fetch_books).to match_array(books) #👈
  end
end