Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Model Serializer, testing which serializer is used to render response

I'm using active model serializers to render JSON responses from a rails controller.

I have a controller action like this:

def show
  @foo = Foo.find(params[:id])
  if @foo.user == current_user
    render json: @foo, serializer: FooSerializer
  else
    render json: @foo, serializer: TrimmedFooSerializer
  end
end

I want to be able to test which serializer has been used in my Rspec controller tests. Is it possible to get a reference to the serializer from the tests?

UPDATE:

I don't think this a correct use of the serializer. I now have logic in the serializer itself to conditionally include attributes. The controller shouldn't really care about which serializer to use.

like image 531
Charlie Avatar asked Feb 28 '14 14:02

Charlie


Video Answer


2 Answers

It has been a while since anyone replied but in case future googlers find this, I like the following approach:

RSpec::Matchers.define :serialize_object do |object|
  match do |response|
    @serializer_klass.new(object).to_json == response.body
  end

  chain :with do |serializer_klass|
    @serializer_klass = serializer_klass
  end
end

Then in your tests you can do:

expect(response).to serialize_object(claim).with(ClaimSerializer)

Note that I didn't call the matcher 'serialize' because shoulda already defines a matcher of that name.

like image 126
Dan Draper Avatar answered Oct 01 '22 16:10

Dan Draper


You can try this. I am assuming that you are using factory_girl. You can write the other test by returning a different user for current_user

describe "show" do
  it "should use FooSerializer to serialize if the logged in user is the same as params user" do
    user = FactoryGirl.create(:user)
    controller.stub(:current_user).and_return(user)
    FooSerializer.any_instance.should_receive(:to_json).and_return("{\"key\": \"value\"")
    get :show, :id => user.id
    response.should be_success
  end
end
like image 26
usha Avatar answered Oct 01 '22 14:10

usha