设计 - 可以使用控制器测试来测试未登录的用户吗?

Devise - possible to use controller test to test user NOT signed in?

我有一个控制器,它依赖于正在验证的用户。所以看起来像这样

class PlansController < ApplicationController
  before_action :authenticate_user!

  def create
    puts "here"
    if user_signed_in?
      puts "true"
    else
      puts "false"
    end
  end
end

当用户登录时,我的控制器测试工作正常,即当我写这样的东西时:

require 'rails_helper'
require 'devise'
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

describe "create action" do
  before do
    @user = User.create(...)
    sign_in :user, @user
  end

  it "should puts here and then true" do
    post :create
    # => here
    # => true
  end
end

但我还想测试 else 语句中发生的情况。不知道该怎么做,它根本上什至没有放置 here。可以测试这个吗?还是我应该离开让 Devise 去?

describe "create action" do
  before do
    @user = User.create(...)
    # do not sign in user (note I have also tried to do a sign_in and then sign_out, same result)
  end

  it "should puts here and then true" do
    post :create
    # => nothing is put, not even the first here!
    # => no real "error" either, just a test failure
  end
end

before_action :authenticate_user! 将立即将您重定向到默认登录页面,如果用户未登录,则完全跳过 create 操作。

在这种情况下,if user_signed_in? 语句没有实际意义,因为当该代码有机会 运行.

时,用户将始终处于登录状态

如果可以在有或没有经过身份验证的用户的情况下创建计划,请删除 before_action 行。