我有一个控制器,它取决于被验证的用户。所以它看起来像这样
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
答案 0 :(得分:2)
The before_action :authenticate_user!
will immediately redirect you to the default sign-in page, if the user isn't signed in, skipping the create
action altogether.
The if user_signed_in?
statement is moot in this case, because the user will always be signed in when that code has the chance to run.
If plans can be created with or without an authenticated user, remove the before_action
line.