控制器规范#Show动作:exoected:[Object],得到:nil错误 - RSpec 3

时间:2015-02-18 16:54:56

标签: ruby-on-rails ruby testing rspec tdd

我正在阅读Aaron Sumner的日常Rails测试与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 helpers:

  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)>'

1 个答案:

答案 0 :(得分:2)

您的问题来自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'上下文来验证操作在您未登录时的行为。