11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails3.2Engineのコントローラーのspecについて

Last updated at Posted at 2012-12-15

複数のプロジェクトで一つのモデルや共通のルーティングを取り扱う時なんかにとても便利なのがEngine。

RailsEngineのコントローラーをテストしてて、routingではまってしまったので、その解決策。

rails g controller hoge index
これで生成したcontrollerのspecは、そのままだとrspecを走らせた時に、以下の様な箇所でルートが見つからない旨のエラーを起こします。

get 'index'

例えばEngine名がMyEngineだったとして、通常のRailsプロジェクトで言えばMyEngineモジュール内のコントローラーはMyEngine::Hoge#indexを参照するはずが、Engineの場合だと、それでは参照できない模様です。
解決策としては、:use_routeでエンジンを指定することがあげられます。

get 'index', :use_route => :my_engine

毎回use_routeと書くのも面倒なので、以下の様なモジュールを書いて、spec_helper.rb内のconfigでincludeしています。

module ControllerSpecHelper
  def get(action, parameters = nil, session = nil, flash = nil)
    process_action(action, parameters, session, flash, "GET")
  end
  
  def post(action, parameters = nil, session = nil, flash = nil)
    process_action(action, parameters, session, flash, "POST")
  end
  
  def put(action, parameters = nil, session = nil, flash = nil)
    process_action(action, parameters, session, flash, "PUT")
  end

  def delete(action, parameters = nil, session = nil, flash = nil)
    process_action(action, parameters, session, flash, "DELETE")
  end
  
  private

  def process_action(action, parameters = nil, session = nil, flash = nil, method = "GET")
    parameters ||= {}
    process(action, parameters.merge!(:use_route => :my_engine), session, flash, method)
  end
end

config内でinclude

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?