LoginSignup
4
6

More than 5 years have passed since last update.

Railsでテスト時のみRoutingを追加する

Posted at

環境

  • Rails 4.2.6, 5.0.0で確認

方法

ActionDispatch::Routing::RouteSet#drawを使ってRails.application.routesに追加します。
ただし#clear!#finalize!が走ると以前の Routing が消えてしまうので、それを抑制するフラグを切り替える必要があります。

# spec/support/additional_routes.rb
class DummiesController < ActionController::Base
  def show
    render plain: 'hi!'
  end
end

Rails.application.configure do
  routes.disable_clear_and_finalize = true

  routes.draw do
    resource :dummy, only: %i(show)
  end

  routes.disable_clear_and_finalize = false
end

rspec-rails を使っているなら、だいたいは feature spec でのみ必要となると思うので type のメタタグを基準に読み込めれば良いです。
RSpec 3.5 ならこんな感じで必要に応じて読み込ませることができます。

# spec/rails_helper.rb
RSpec.configure do |config|
  config.when_first_matching_example_defined(type: :feature) { require 'support/additional_routes' }
end

参考リンク

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6