Search code examples
jsonruby-on-rails-3testingrspeccancan

How do I create an rspec test that validates a JSON response?


I have a Groups Controller with a method def inbox.

If the user is a group member then inbox returns a JSON object.

If the user is not a member, then inbox should redirect thanks to CanCan permissions.

How do I write an rspec to test these two use cases?

Current spec:

require 'spec_helper'

describe GroupsController do
  include Devise::TestHelpers

  before (:each) do
    @user1 = Factory.create(:user)
    @user1.confirm!
    sign_in @user1
    @group = Factory(:group)
    @permission_user_1 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group)
  end

  describe "GET inbox" do
    it "should be successful" do
      get inbox_group_path(@group.id), :format => :json
      response.should be_success
    end
  end
end

Routes:

inbox_group GET /groups/:id/inbox(.:format) {:controller=>"groups", :action=>"inbox"}

Routes File:

resources :groups do
  member do
    get 'vcard', 'inbox'
  end
  ....
end

Solution

  • This is how I do this:

    describe "GET index" do
      it "returns correct JSON" do
        # @groups.should have(2).items
        get :index, :format => :json
        response.should be_success
        body = JSON.parse(response.body)
        body.should include('group')
        groups = body['group']
        groups.should have(2).items
        groups.all? {|group| group.key?('customers_count')}.should be_true
        groups.any? {|group| group.key?('customer_ids')}.should be_false
      end
    end
    

    I'm not using cancan, therefore I cannot help with this part.