我有一个控制器,它依赖于正在进行身份验证的用户。它看起来像这样
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
。有可能测试这个吗?还是我该离开,让设计自生自灭?
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
行。