簡體   English   中英

Rails控制器Rspec測試

[英]Rails Controller Rspec Test

作為前言,我是Rails和一般MVC格式的新手。

我正在使用Rspec進行所有測試,我在controller_spec中遇到了這段代碼的問題:

describe "GET show" do
    context 'with an admin user signed in' do
      with :admin
      let!(:invitation) { create :invitation }   
      before do
        sign_in admin
        get :show, id: invitation.id
      end
      it { should respond_with :ok }
      it { should respond_with_content_type :html }
      it { should render_template :show }
      it "assigns the requested invitation as @invitation" do
        expect(assigns(:invitations)).to eq([invitation])
      end
    end
  end

這是我得到的錯誤:

14) InvitationsController GET show with an admin user signed in assigns the requested invitation as @invitation
     Failure/Error: expect(assigns(:invitations)).to eq([invitation])

       expected: [#<Invitation id: 98, token: "blah", name: "Team", number_of_uses: 5, created_at: "2016-01-29 20:43:27", updated_at: "2016-01-29 20:43:27">]
            got: nil

       (compared using ==)
     # ./spec/controllers/invitations_controller_spec.rb:53:in `block (4 levels) in <top (required)>'

最后,這里分別是我的控制器和策略類片段。

控制器:

class InvitationsController < ApplicationController
  before_action :set_invitation, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    authorize Invitation
    @invitations = policy_scope(Invitation)
    respond_with(@invitations)
  end

  def show
    authorize @invitation
    respond_with(@invitation)
  end

invitation_policy.rb:

class InvitationPolicy < ApplicationPolicy
  Scope = Struct.new(:user, :scope) do
    def resolve
      Invitation.all
    end
  end

  def index?
    user.admin?
  end

  def show?
    user.admin?
  end

我在這里使用的相關寶石是Pundit和FactoryGirl。 我還在學習很多這些東西的含義,所以我很清楚答案可能很明顯。

你的規格是錯的。 它檢查@invitations是否設置為一組邀請(這可能適合於索引操作),但您的show動作會為@invitation分配一個邀請。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM