Question

I setup this 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

and this from my ApplicationController

class ApplicationController < ActionController::Base   
  serialization_scope :view_context

  protected 
  def current_client
      ....

I put in the "delegate" code based on this railscast around 7:45

He then goes on to say that the downside is that the tests now need a view_context and gives a solution for using Test Unit.

When I run my specs I get one of two errors

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

or

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:

How do I provide the view_context in my controller specs?

Thanks.

Was it helpful?

Solution

OK. My fault. I was calling the UserSerializer manually in my code later to do assertions. That's what was throwing the error. Fixed it just by adding:

before(:each) do
  UserSerializer.any_instance.stub(:scope => controller)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top