Controller Spec #Show Action: exoected: [Object], got: nil 错误 - RSpec 3

Controller Spec #Show Action: exoected: [Object], got: nil Error - RSpec 3

我正在阅读 Aaron Sumner 的 Everyday Rails Testing with RSpec (3) 书,但无法通过以下步骤:

我正在尝试指定 users#show 操作:

users_controller_spec:

...    
describe 'GET #show' do

  it "assigns the requested contact to @user" do
    user = create(:user)
    get :show, id: user.id
    expect(assigns(:user)).to eq user
  end


  it "renders the :show template" do
    user = create(:user)
    get :show, id: user.id
    expect(response).to render_template :show
  end

end
...

users_controller:

class UsersController < ApplicationController
  before_action :authenticate
  before_action :set_user, only: [:show]

  ### Read:
  def show
    ...
  end


  private

  def set_user
    @user = User.find(params[:id])
  end

end

application_controller 帮手:

  def authenticate
    redirect_to home_path, alert: 'Please log in first' if current_user.nil?
  end

  private 

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

错误:

Failures:

  1) UsersController GET #show assigns the requested user to @user
     Failure/Error: expect(assigns(:user)).to eq user

       expected: #<User id: 1, ...">
            got: nil

       (compared using ==)
     # ./spec/controllers/users_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

  2) UsersController GET #show renders the :show template
     Failure/Error: expect(response).to render_template :show
       expecting <"show"> but rendering with <[]>
     # ./spec/controllers/users_controller_spec.rb:17:in `block (3 levels) in <top (required)>'

您的问题来自 before_action :authenticate 您需要在规范中将自己设置为已通过身份验证,或者您需要跳过 show 操作的身份验证。

你通常会这样测试:

context 'when logged in' do
  before(:each) do
    set_as_logged_in
  end

  # your specs
end

其中 set_as_logged_in 方法会根据您进行身份验证的方式而有所不同。然后您还可以有一个 'when not logged in' 上下文来验证操作在您未登录时是否按预期运行。