LoginSignup
6
5

More than 5 years have passed since last update.

Rails4でEngineのcontroller specで必ずuse_routeする

Last updated at Posted at 2014-07-23

問題

Rails::Engineをmountして、そのルートへのリクエストのcontroller specを書きたい場合、

get :index

みたいにやるとNo route matchesと言われてしまう。

そのため、毎度

get :index, use_route: :my_engine

みたいに書かないといけないのだけれど、これが死ぬほどめんどくさい。

解決策

Rails3.2Engineのコントローラーのspecについて のように、
get, post, put, deleteをしたときにActionController::TestCase::Behavior.processに渡されるパラメータにuse_route: :my_engineを含めてやればよい。

rails4だとpatchもあるわけで、process自体をオーバーライドしてしまったほうがシンプルに書けるし良いと思われる。
processの定義はここなんだけど、今はメソッドのシグネチャが違う気がする。
以上を鑑みて、以下のようにspec_helperをいじるなりspecのsupportファイルを書く。

module ControllerSpecHelper
  def process(action, http_method = 'GET', *args)
    parameters, session, flash = args
    super(action, http_method, (parameters || {}).merge(use_route: :my_engine), session, flash)
  end
end

RSpec.configure do |config|
  config.include ControllerSpecHelper, type: :controller
end
6
5
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
6
5