94
101

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.

deviseを使ったコントローラのテスト

Last updated at Posted at 2012-05-31

deviseを使って認証しているコントローラのテストを書くには、wikiに書いてある通り以下のようにすれば良い。

spec/supportにcontroller_macros.rbを追加

controller_macros.rb
module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in FactoryGirl.create(:user)
    end
  end
end

spec_helperに以下を追加

spec_helper.rb
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
  # 以下略

controller_specのテストしたい箇所に以下を追加

users_controller_spec.rb
  describe "ログインしている場合" do
    login_user

    # 以下略

が、コントローラでbefore_filter :authenticate_user!にしているとsign_inしているにも関わらずroot_pathにリダイレクトされてしまう。それを防ぐには、controller_macrosにスタブを追加する。

controller_macros.rb
module ControllerMacros
  def login_user
    before(:each) do
      controller.stub(:authenticate_user!).and_return true
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in FactoryGirl.create(:user)
    end
  end
end

ただしこれがベストプラクティスかどうかは自信がない・・・

94
101
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
94
101

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?