Search code examples
ruby-on-rails-3jsonrestcucumberacceptance-testing

Testing JSON API that uses Devise token authenticable module with Cucumber


I am writing acceptance tests for a RESTfull JSON service. I want to be able to run the tests against production server. This API is used by the iphone client. For authentication the JSON service uses the Devise authentication token module.

Here is the protocol in a nutshell:

iphone: POST /api/v1/tokens with params email=user@serivce.com&pass=secretpass server: return 200 and the following JSON {"token":"UYUKJHBKHJJHSAD"} iphone: GET /api/v1/messages?auth_token=UYUKJHBKHJJHSAD

Everything works great.

What is the best way to test this with Cucumber?

I am using the api_steps from https://github.com/jayzes/cucumber-api-steps and I hacked something together so that the auth_token is passed with every GET request however it is a bit of an hack.

What I did is to create the following step:

And I authenticate as the user "admin@myservice.com" with the password "bingobingo"

in it I set a global variable auth_token that I then append to all the GET requests. UGLY!

I am asking to you Cucumber/Rails/Test gurus! What is the best way of doing this?


Solution

  • I've found RSpec easier to use than Cucumber.

    # spec/api/messages_spec.rb
    describe "messages", :type => :api do
      it "retrieves messages" do
        get "/api/v1/messages", :token => user.authentication_token
        @messages = user.messages # this is the expected result
        last_response.body.should eql @messages.to_json
        last_response.status.should eql 200
      end
    end
    
    # spec/support/api/helper.rb, so we have access to get, post, put, delete methods
    module ApiHelper
      include Rack::Test::Methods
      def app
        Rails.application
      end
    end
    RSpec.configure do |c|
      c.include ApiHelper, :type => :api
    end