为什么我的rspec测试失败了?

时间:2016-03-08 13:46:55

标签: ruby-on-rails rspec

我正在为我的ShowcasesController编写一个测试,并且我已经停留在“GET new”操作中,用于登录用户。

require 'rails_helper'
require 'spec_helper'

RSpec.describe ShowcasesController, type: :controller do

  context "user is signed in" do

    before do
      @user = create(:user)
      @admin = create(:admin)
      @showcase = create(:showcase)
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in(@user)
    end

    describe "GET new" do
      context "user is not admin" do
        it "redirect to root page" do
          get :new
          expect(response).to redirect_to(root_url)
        end
      end

      context "user is an admin" do
        it "expose a new showcase" do
          sign_in(@admin)
          get :new
          expect(controller.showcase).to be_a_new(Showcase)
        end
      end
    end
  end
end

由于未知原因,我的测试失败了,我正在接受这个错误按摩:

  

故障:

     

1)ShowcasesController用户在GET中签名新用户是管理员   揭露一个新的展示        失败/错误:期望(controller.showcase).to be_a_new(Showcase)

 NoMethodError:
   undefined method `showcase' for #<ShowcasesController:0x00000004d7c400>
 # ./spec/controllers/showcases_controller_spec.rb:104:in `block (5 levels) in <top (required)>'
class ShowcasesController < ApplicationController
  before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
  before_action :correct_user, only: [:new, :edit, :update, :destroy]

  def index
    @showcases = Showcase.all
  end

  def show
    @showcase = Showcase.find(params[:id])
  end

  def new
    @showcase = Showcase.new
  end

  def create
    @showcase = Showcase.new(showcase_params)
    if @showcase.save
    end
  end

  def edit
    @showcase = Showcase.find(params[:id])
  end

  def update
    @showcase = Showcase.find(params[:id])
    if @showcase.update_attributes(showcase_params)
    end
  end

  def destroy
    @showcase = Showcase.find(params[:id]).destroy
  end

  private

  def showcase_params
    params.require(:showcase).permit(:first_name, :last_name, :sport_club, :email, :pass_exam_date, :pass_exam_location,
    :exam_type, :level, :first_graduation_date, :second_graduation_date, :third_graduation_date, :fourth_graduation_date,
    :total_match_number, :match_number_in_last_season)
  end

  def correct_user
    unless current_user.admin?
      redirect_to root_url
    end
  end
end

2 个答案:

答案 0 :(得分:4)

控制器上没有定义showcase方法,只有一个实例变量。

要检查控制器上的实例变量,rspec控制器测试提供assigns功能:

expect(assigns :showcase).to be_a_new(Showcase)

注意:据我所知,目前有一些计划从rspec中删除assigns。我认为做出这个决定是因为它违反了“不测试私人实施细节”的说法。 - 我个人不喜欢这个决定,因为这将使控制器单元测试更加困难。 IMO,即使它是实例变量,它也被用于在控制器和视图之间进行通信,因此它是控制器公共API的一部分。 (将公共API的实例变量用于地狱,这很糟糕。)

答案 1 :(得分:0)

发生错误是因为尚未为showcase定义方法ShowcasesController。更确切地说,尚未为控制器的showcase属性定义访问器。

An example with an accessor
class ShowcasesController
  attr_accessor :showcase

  # other controller methods
end