ruby-on-rails – 如何在rspec功能测试中访问(设计)current_user
发布时间:2020-12-16 22:15:21 所属栏目:百科 来源:网络整理
导读:在设计文档中,他们提供了有关在测试控制器时如何访问current_user的提示: https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29 但是,在进行功能测试时呢?我试图测试我的一个控制器的创建方法,在该
在设计文档中,他们提供了有关在测试控制器时如何访问current_user的提示:
https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29 但是,在进行功能测试时呢?我试图测试我的一个控制器的创建方法,在该控制器中使用current_user变量. 问题是,devise中建议的宏使用@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下定义了这个 解决方法
从
https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29
如果我明白你对,也许你需要使用 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |