Chi*_*fic 23 rspec ruby-on-rails stub ruby-on-rails-4
我有一个基于MHartl的RoR4教程的控制器
就像MHartl一样,我没有使用Devise,我推出了自己的身份验证系统
由于UsersController#Edit视图有一个调用current_user.admin?和控制器调用,因此RSpec出现问题@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 <top (required)>'
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仍然会回来nil
任何帮助/指导表示赞赏.谢谢!
添加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:
<% if current_user.admin? %>
  <div class="row  col-xs-6 col-sm-6 col-md-3">
    <div class="input-group input-selector">
    ...
我需要做的就是弄清楚如何设置current_user.admin = true并将其传递给控制器(然后希望视图),以便页面可以加载.要做到这一点,我需要做的就是设置current_user = user因为user.admin == true.
Ben*_*enj 36
如果你正在对你的控制器进行单元测试,你可以简单地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 } }
如果您正在进行功能或请求测试,我建议您通过在数据库中创建用户,然后使用此用户凭据传递登录页面来执行真正的登录
在这里,您似乎正在进行功能测试,您应该编写一个帮助程序来执行用户记录的创建并完成登录.
此外,在功能测试中,为了在运行测试时获得大量时间,请不要犹豫,将断言分组到同一个块中.显然,而不是:
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
这样可以避免生成多个功能环境会话,也可以多次登录
也有效
user = create(:user) #FactoryBot
allow(controller).to receive(:current_user).and_return(user)
| 归档时间: | 
 | 
| 查看次数: | 11066 次 | 
| 最近记录: |