LoginSignup
4
1

More than 3 years have passed since last update.

RSpec で devise.gem の user_signed_in? をモックする

Last updated at Posted at 2018-05-18

Devise::Controllers::Helpers#user_signed_in? をモックする。コードはこのへん(plataformatec/devise)Devise で使ってるモデルが User じゃない場合は適宜変更すればOK。

before do
  allow_any_instance_of(Devise::Controllers::Helpers).to receive(:user_signed_in?).and_return(false)
end

ただし allow_any_instance_of の使用は非推奨なので注意。 cf. rspec/rspec-mocks, rspecでallow-any-instance-ofは使わない方がよい、が身に沁みたので別の方法で試してみる

追記

allow_any_instance_of つかわずにテスト対象のモジュールに対してモックすれば十分なことが多い。

# helper がテスト対象のインスタンスの場合
before do
  allow(helper).to receive(:user_signed_in?).and_return(false)
end
4
1
2

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
4
1