在设计文档中,他们提供了有关如何在测试控制器时访问current_user的提示:
然而,在进行功能测试时呢?我正在尝试测试我的一个控制器的create方法,并在该控制器中使用current_user变量。
问题是设计中建议的宏使用@request变量,并且对于特征规范它是零。什么是变通方法?
编辑:
这是我目前的规格:
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
未定义,因此会将我重定向到/users/sign_in
。
我已在/spec/features/manage_orders.rb
答案 0 :(得分:27)
如果我理解你的话,也许你需要使用
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:
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中:
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
答案 1 :(得分:2)
以下是我认为您正在寻找的内容:
require 'spec_helper'
include Warden::Test::Helpers
Warden.test_mode!
feature 'As a user I manage the orders of the system' do
scenario 'User is logged in ad an admin' do
user = create(:user)
login_as(user, scope: :user)
order = create(:order, user: user)
visit orders_path
#Expectations
end
end
答案 2 :(得分:1)
您可以将login_user定义为用户登录的方法,如下所示(将其放在支持文件夹中):
def login_user
Warden.test_mode!
user = create(:user)
login_as user, :scope => :user
user.confirmed_at = Time.now
user.confirm!
user.save
user
end
然后在场景中说:
user = login_user