Webuilder240

RSpecでメソッドを呼ばれたことを検証する

2020-09-05 00:52:27 +0900

RSpec Rails Ruby
RspecでメソッドがCallされたことだけをテストする方法を最近調べたので記載しておく。

ここでは、いわゆるSpyを使って実現している。

https://techracho.bpsinc.jp/hachi8833/2018_03_12/53518

class Post < ApplicationRecord
  def logging
    DummyFluentd.logging({
      post: {
        title: title,
        content: content
      }
    })
  end
end

class DummyFluentd
  def self.logging(params = {})
    Rails.logger.info("============== test ==================")
    Rails.logger.info("============== #{params} ==================")
    Rails.logger.info("============== test ==================")
  end
end

# post_spec.rb
require 'rails_helper'
RSpec.describe Post, type: :model do
  let(:new_post) { Post.new(title: "test", content: "content") }
  before do
    allow(DummyFluentd).to receive(:logging)
  end
  context "new_post" do
    it "call dummy fluentd logging method" do
      new_post.logging
      expect(DummyFluentd).to have_received(:logging)
      .once
      .with({
        post: 
          {
            title: new_post.title,
            content: new_post.content
          }
     })
    end
  end
end

expect(クラス名).to have_received(:メソッド名).onceで「1度だけ」メソッドの呼び出しを検証している。また、.withをつけることで、受け取った引数の検証も行うことができる。

この記事にあるように何度呼び出されたのかも検証することができる。
https://shingo-sasaki-0529.hatenablog.com/entry/how_to_use_rspec_mocks

どういうときに使えるテクニックなのか?

Fluentdでログ送信を行うときに実際にログが送信されているかをチェックするのは難しいけど、少なくともメソッドが呼び出されていることを検証したい場合に有効。というかこのために調べたのでした。

関連しそうなブログ