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