2016-02-01 291 views
2

爲了序言,我對Rails和通用MVC格式非常陌生。Rails控制器Rspec測試

我使用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 

我使用的是這裏的有關寶石權威人士和FactoryGirl。我仍然在學習很多這些東西的含義,所以我很清楚答案可能很明顯。

+0

你的'sign_in admin'在做什麼?你是否在扼殺'sign_in'? – Leito

回答

3

您的配置錯誤。它會檢查@invitations是否設置爲一系列邀請(這可能適用於索引操作),但您的顯示操作會將一個邀請分配給@invitation

+0

很好的發現,答案總是比他們看起來簡單。 – Leito