LoginSignup
30
26

More than 5 years have passed since last update.

Rspecでcurrent_userのスタブを作ってrequire_loginをパスする

Last updated at Posted at 2014-03-25

Sorcery等によって提供されるcurrent_user、require_loginを使ったrailsアプリを、rspecでテストする方法を共有します。

実現方法

current_userのスタブを作ります。

テストの記述方法

items_controller_spec.rb
before do
  @user = User.first
  allow(controller)
    .to receive(:current_user)
    .and_return(@user)
end

説明

controllercurrent_userのスタブを作ることによって、before_action require_loginを通過できます。

以上です。
ログイン機能を実際に経由して本物のcurrent_userを呼び出す方法を確立している方がいらっしゃいましたら、方法を共有して頂けると嬉しいです。

http://stackoverflow.com/questions/5865555/how-to-do-integration-testing-with-rspec-and-devise-cancan
http://stackoverflow.com/questions/3720953/rspec-accessing-application-controller-methods-such-as-current-user

30
26
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
30
26