RSpec:如何存根inheritance方法current_user(没有设计)?

我有一个基于MHartl的RoR4教程的控制器

就像MHartl一样, 我没有使用Devise ,我推出了自己的身份validation系统

因为视图调用current_user.admin?无法使用RSpec for UsersController#Edit current_user.admin? 并且控制器调用@path_switch = path_switch

我不断得到RSpec错误:

 1) User Pages Edit Failure/Error: visit edit_user_path(user) NoMethodError: undefined method `admin?' for nil:NilClass # ./app/controllers/users_controller.rb:106:in `path_switch' # ./app/controllers/users_controller.rb:53:in `edit' # ./spec/requests/user_pages_spec.rb:54:in `block (3 levels) in ' 

UsersController:

 class UsersController < ApplicationController ... def edit @user = User.find(params[:id]) @path_switch ||= path_switch #error end ... def path_switch if current_user.admin? #error users_path else root_path end end end 

我发现这篇非常有用的文章让我希望我能走上正轨,但我无法让它发挥作用。

据我所知(更新):

user_pages_spec.rb:

 require 'spec_helper' require 'support/utilities' describe "User Pages" do #include SessionsHelper let(:user) { FactoryGirl.create(:user) } let(:current_user) {user} subject { page } describe "Edit" do before do sign_in(user) visit edit_user_path(user) end it '(check links and content)' do should have_button('Submit') should have_link('Cancel') should have_content(user.fname+"\'s profile") end ... end ... end 

但是current_user仍然没有回来

任何帮助/指导表示赞赏。 谢谢!


添加include SessionsHelper到我的user_pages_edit.rb的顶部描述块似乎尝试使用该帮助器中的sign_in(路径)。 在RSpec和cookies.permanent之间创建一个问题 。 这是一个半身像。

不幸的是 ,这让我回到了我的.admin? 错误。

有两次调用current_user.admin?

一个在控制器中:

  def path_switch if current_user.admin? #error current_user == nil users_path else root_path end end 

其中一个是ERB:

  
...

我需要做的就是弄清楚如何设置current_user.admin = true并将其传递给控制器​​(然后希望视图),以便页面可以加载。 要做到这一点,我需要做的就是设置current_user = user因为user.admin == true

如果您正在对控制器进行unit testing ,则可以在before块中将current_user存根,如下所示:

 let(:user) { ... } # RSpec version <= 2 syntax: before { controller.stub(:current_user) { user } } # RSpec version >= 3 syntax: before { allow(controller).to receive(:current_user) { user } } 

如果您正在进行function或请求测试 ,我建议您通过在数据库中创建用户,然后使用此用户凭据传递登录页面来执行真正的登录


在这里,您似乎正在进行function测试,您应该编写一个帮助程序来执行用户记录的创建并完成登录。

此外,在function测试中,为了在运行测试时获得大量时间,请不要犹豫,将断言分组到同一个块中。 显然,而不是:

 it { should have_button('Submit')} it { should have_link('Cancel')} it { should have_content(user.fname+"\'s profile")} 

你可以写

 it 'check links and content' do should have_button('Submit') should have_link('Cancel') should have_content(user.fname+"\'s profile") end 

这样可以避免生成多个function环境会话,也可以多次登录

也有效

 user = create(:user) #FactoryGirl allow(controller).to receive(:current_user).and_return(user) 

对我来说,与…合作:

 before { controller.stub!(:current_user).and_return(user) }