タケユー・ウェブ日報

Ruby on Rails や Flutter といったWeb・モバイルアプリ技術を武器にお客様のビジネス立ち上げを支援する、タケユー・ウェブ株式会社の技術ブログです。

Rails RSpec のコントローラテストでデフォルトのパラメータを設定できるようにしてみる。

以前RSpecの拡張の練習がてら、こういうのを

require 'spec_helper'

describe Api::SpotsController do
  describe "GET 'index'" do
    it "returns http success" do
      get 'index', format: 'json'
      response.should be_success
    end
  end

  describe "GET 'show'" do
    let(:spot){ create(:spot) }
    it "returns http success" do
      get 'show', id: spot.id, format: 'json'
      response.should be_success
    end
  end
end

こうかけるようにしたコードを書いていたので、思いだしメモ。

require 'spec_helper'

describe Api::SpotsController do
  default_params format: 'json'
  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end

  describe "GET 'show'" do
    let(:spot){ create(:spot) }
    it "returns http success" do
      get 'show', id: spot.id
      response.should be_success
    end
  end
end

spec/support/process_with_default_params.rb

class ActionController::TestCase < ActiveSupport::TestCase
  module Behavior
    def process_with_default_params(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
      parameters ||= {}
      parameters.reverse_merge! self.default_params
      process_without_default_params(action, parameters, session, flash, http_method)
    end
    alias_method_chain :process, :default_params
  end
end

module ProcessWithDefaultParams

  module ExampleGroupMethods
    def default_params(params)
      let(:__default_params){ params }
    end
  end

  module ExampleMethods
    def default_params
      self.respond_to?(:__default_params) ? __default_params : {}
    end
  end

  def self.included(mod)
    mod.extend ExampleGroupMethods
    mod.__send__ :include, ExampleMethods
  end
end

RSpec.configure do |config|
  config.include ProcessWithDefaultParams
end