【问题标题】:How do I get a view_context in my controller specs for testing active model serializers如何在我的控制器规范中获取 view_context 以测试活动模型序列化程序
【发布时间】:2013-10-11 14:49:31
【问题描述】:

我设置了这个 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

这个来自我的 ApplicationController

class ApplicationController < ActionController::Base   
  serialization_scope :view_context

  protected 
  def current_client
      ....

我在 7:45 左右输入了基于 this railscast 的“委托”代码

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

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

失败/错误:获取“显示”,:id => user.id,:格式=>:json 无方法错误: #

的未定义方法`current_client'

失败/错误:data.active_model_serializer.new(data, {:root => 名称}).to_json 运行时错误: UserSerializer#current_client 委托给 scope.current_client,但范围为零:

如何在我的控制器规范中提供 view_context?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby rspec active-model-serializers


    【解决方案1】:

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

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

    【讨论】:

    • 你是在哪里添加的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2017-01-14
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多