gpt4 book ai didi

ruby-on-rails - 如何在我的 Controller 规范中获取 view_context 以测试事件模型序列化程序

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:15 24 4
gpt4 key购买 nike

我设置了这个 UserSerializer

class UserSerializer < ActiveModel::Serializer
attributes :id, :first_name, :last_name, :email, :abilities

delegate :current_user, to: :scope
delegate :current_client, to: :scope

def abilities
object.client_roles.where(client_id: current_client.id)
end
end

这来 self 的 ApplicationController

class ApplicationController < ActionController::Base   
serialization_scope :view_context

protected
def current_client
....

我输入了基于 this railscast 的“委托(delegate)”代码大约 7:45

然后他继续说缺点是测试现在需要一个 view_context 并给出了使用测试单元的解决方案。

当我运行我的规范时,我遇到了两个错误之一

Failure/Error: get "show", :id => user.id, :format => :json      NoMethodError:        undefined method `current_client' for #<#:0x00000004f69f60>

Failure/Error: data.active_model_serializer.new(data, {:root => name}).to_json RuntimeError: UserSerializer#current_client delegated to scope.current_client, but scope is nil:

如何在我的 Controller 规范中提供 view_context?

谢谢。

最佳答案

好的。我的错。稍后我在我的代码中手动调用 UserSerializer 来进行断言。这就是引发错误的原因。只需添加即可修复它:

before(:each) do
UserSerializer.any_instance.stub(:scope => controller)
end

关于ruby-on-rails - 如何在我的 Controller 规范中获取 view_context 以测试事件模型序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19321108/

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