Ruby on rails 登录用户可以';我好像没有签到
我使用M.HartlRails教程创建了我的应用程序。因此,我有一个Ruby on rails 登录用户可以';我好像没有签到,ruby-on-rails,authentication,rspec,capybara,Ruby On Rails,Authentication,Rspec,Capybara,我使用M.HartlRails教程创建了我的应用程序。因此,我有一个User模型,以及所有current\u User和signed\u-in\u-User方法 我想通过以下测试: describe "submitting a PATCH request to the Users#update action" do before do be_signed_in_as FactoryGirl.create(:user) patch user_path(FactoryGirl.c
User
模型,以及所有current\u User
和signed\u-in\u-User
方法
我想通过以下测试:
describe "submitting a PATCH request to the Users#update action" do
before do
be_signed_in_as FactoryGirl.create(:user)
patch user_path(FactoryGirl.create(:user))
end
specify { expect(response).to redirect_to(root_path) }
end
但测试失败了:
Failure/Error: specify { expect(response).to redirect_to(root_path) }
Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>.
Expected "http://www.example.com/" to be === "http://www.example.com/signin".
Failure/Error:指定{expect(response).to redirect_to(root_path)}
预期响应为重定向到,但为重定向到。
预期的”http://www.example.com/“未来==”http://www.example.com/signin".
下面是用户控制器的一部分
class UsersController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
.
.
.
.
private
def signed_in_user
unless !current_user.nil?
store_url
redirect_to signin_url, notice: t('sign.in.please')
end
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
class UsersController
如果在用户…行中删除\u create:signed\u之前的,则测试通过。
但为什么呢?be\u signed\u in\u as
spec方法在所有其他测试(~1k)中都起作用,因此原因必须在specify{expect(response)中
事情。您的测试将转到一个与您登录身份不同的用户的用户路径
,因此您的正确的用户
过滤器将重定向到根目录。您需要保存您登录身份的用户,并在每次调用FactoryGirl.create时将其用于用户路径(:user)
,您正在创建一个额外的用户。您列出的代码正在数据库中创建两个单独的用户记录。因此,除非您打算为此测试创建两个不同的用户,否则您可能应该在之前的块前面有一行,如:
let(:user) { FactoryGirl.create(:user) }
然后只要在你想要一个用户记录的任何地方引用user
。除非!当前用户.nil?
这几乎是你在这种情况下可以编写的最糟糕的逻辑。这是不是意味着如果当前用户.nil?
或者除非当前用户.present?
?不过,我假设补丁请求没有成功将会话cookie发送到您的应用程序,这样就没有当前用户了,我如何才能模拟会话cookie?