在rspec功能测试中如何访问(devise)current_user? [英] How to access (devise) current_user in a rspec feature test?
问题描述
在设计文档中,他们会提供有关在测试控制器时如何访问current_user的提示:
In the devise documentation they give tips on how you can have access to current_user when testing a controller:
然而,在做一个功能的时候呢测试?我试图测试一个我的控制器的创建方法,在该控制器中使用current_user变量。
However, what about when doing a feature test? I am trying to test a create method of one of my controllers, and in that controller is used the current_user variable.
问题是,devise中建议的宏使用@request变量,功能规格为零。什么是解决方法?
The problem is that the macro suggested in devise uses the @request variable, and it is nil for a feature spec. What is a workaround?
编辑:
这是迄今为止我目前的规范: / p>
This is what I have so far for my current spec:
feature 'As a user I manage the orders of the system' do
scenario 'User is logged in ad an admin' do
user = create(:user)
order = create(:order, user: user)
visit orders_path
#Expectations
end
end
问题是在我的 OrdersController
有一个 current_user.orders
调用,并且由于 current_user
没有定义,它将重定向到$ code > / users / sign_in 。
The problem is that in my OrdersController
I have a current_user.orders
call, and since current_user
is not defined, it will redirect me to /users/sign_in
.
我已经在 /spec/features/manage_orders.rb
推荐答案
如果我理解你的权利,也许你需要使用
if i have understood you right, maybe you need to use
subject.current_user.email
#or
controller.current_user.email
例如:
describe OrdersController, :type => :controller do
login_user
describe "POST 'create'" do
it "with valid parametres" do
post 'create', title: 'example order', email: subject.current_user.email
end
end
end
controller_macros.rb:
controller_macros.rb :
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
#user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
不要忘记将其包含在spec_helper.rb中:
Don't forget to include this into your spec_helper.rb :
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
这篇关于在rspec功能测试中如何访问(devise)current_user?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!