LoginSignup
1
0

More than 5 years have passed since last update.

[Rails] trailing_slash: trueなルーティングのテストに失敗するとき

Last updated at Posted at 2018-05-21

RailsのController Specで、trailing_slash: trueなrouteをテストしようとしてハマった。

具体例

config/routes.rb
get 'test/ok', to: 'test#ok'
get 'test/ng', to: 'test#ng', trailing_slash: true
app/controllers/test_controller.rb
def ok
  render plain: test_ok_path # => /test/ok
end

def ng
  render plain: test_ng_path # => /test/ng/
end

ブラウザからそれぞれアクセスする(末尾スラッシュは付けても付けなくても構わない)と正しく動作する。
しかし、test#ngのテストを普通に書くとNo route matchesになってしまう。

spec/controllers/test_controller_spec.rb
describe 'GET #ok' do
  subject { get :ok }
  it { is_expected.to be_successful }
end

describe 'GET #ng' do
  subject { get :ng }
  it { is_expected.to be_successful }
end
ActionController::UrlGenerationError:
  No route matches {:action=>"ng", :controller=>"test"}

解決方法

getの引数paramstrailing_slash: trueを含めればよい。

spec/controllers/test_controller_spec.rb
describe 'GET #ng' do
  subject { get :ng, params: { trailing_slash: true } }
  it { is_expected.to be_successful }
end

paramsに入れるのってクエリパラメータだけじゃないんですね…。
公式ドキュメントの記述は見つけられていないので、ご存知の方がいれば教えてほしい。

1
0
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
1
0