17
17

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.

capybara/rspecで認証をスタブする

Last updated at Posted at 2012-09-11

よく見る認証の構造で、(こういうやつ)

app/controllers/ApplicationController.rb
# encoding: utf-8

class ApplicationController < ActionController::Base
	before_filter :authenticate
	helper_method :current_user

	def authenticate
		# 認証
	end

	def current_user
		# ユーザーの取得
	end
end

セッションからレコードを呼び出すと思いますが、
capybaraでセッションをうまく扱えなかったので(知っている方投稿してほしいです)スタブで回避しました。

spec/integration/authenticate_spec.rb
# ~

it "ユーザーが取得できなければリダイレクトされるべき" do
	visit "/foo/bar"
	current_path.should == "/" 
end

describe "ユーザーが取得できるとき" do
	before (:each) do
		@user = User.create({:name => "foo", :email => "bar@example.com" })
		
		# ApplicationControllerを継承する全てのインスタンスの:current_userをスタブ
		ApplicationController.any_instance.stub(:current_user).and_return(@user)
	end

	it "認証をパスしてリクエスト通りのレスポンスを返すべき" do
		visit "/foo/bar"
		current_path.should == "/foo/bar"
	end
end
 

rack_session_accessというgemでいけるようなのですが、
READMEどおりにやってうまくいかなかった(GET /rack_session/edit しようとした)のでメモ。

17
17
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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?