gpt4 book ai didi

ruby-on-rails - Rails Controller Rspec 测试

转载 作者:数据小太阳 更新时间:2023-10-29 07:59:02 26 4
gpt4 key购买 nike

作为序言,我对 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)>'

最后,这里分别是我的 Controller 和策略类片段。

Controller :

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

我在这里使用的相关 gem 是 Pundit 和 FactoryGirl。我仍在学习很多这些东西的含义,所以我很清楚答案可能是显而易见的。

最佳答案

您的规范有误。它检查 @invitations 是否设置为一组邀请(这可能适用于 index 操作),但您的 show 操作将单个邀请分配给 @invitation

关于ruby-on-rails - Rails Controller Rspec 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35137298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com