Skip to content

Instantly share code, notes, and snippets.

@jmcervera
Forked from alex-zige/gist:5795358
Created April 10, 2014 10:33
Show Gist options
  • Select an option

  • Save jmcervera/10366285 to your computer and use it in GitHub Desktop.

Select an option

Save jmcervera/10366285 to your computer and use it in GitHub Desktop.

Respec APIs Testing Notes

Folder Structure

  spec
  |--- apis #do not put into controllers folder. 
        |--- your_api_test_spec.rb  
  |--- controllers
  |--- models
  |--- supports
        |--- api_helper.rb
        |--- authentication_helper.rb

*note: do not put your apis folder underneath controllers folder, otherwise, it will inherited with controller ActionController::TestCase::Behavior, Rake::Test::Methods cannot be apply accordingly.

Custom Rspec Helper for Rake::Test::Methods for api scopes.

@spec/supports/api_helper.rb


module ApiHelper
  include Rack::Test::Methods

  def app
    Rails.application
  end
end

RSpec.configure do |config|
  config.include ApiHelper, :type=>:api #apply to all spec for apis folder
end

Enable Spec_helper supports

@spec/spec_helper.rb
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

API Test Spec

make sure your sample test group has type: api, then it will include Rake::Test::Methods for (get,post,put,delete) requests

@spec/apis/authentication_spec.rb

require "spec_helper"

describe "API authentication" , :type => :api do

  let!(:user) { FactoryGirl.create(:user) }

  it "making a request without cookie token " do
    get "/api/v1/items/1",:formate =>:json
    last_response.status.should eql(401)
    error = {:error=>'You need to sign in or sign up before continuing.'}
    last_response.body.should  eql(error.to_json)
  end

end  

##Interesting points.

ActionController::TestCase::Behavior v.s. Rack::Test::Methods Rspec Rails includes ActionController::TestCase::Behavior for simulating controller requests. so you could do

require "spec_helper"

describe Api::V1::SessionsController , :type => :api do

  let!(:user) { FactoryGirl.create(:user) }

  it "making a request without cookie token " do
    get :index
    response.status.should eql(401)
    error = {:error=>'You need to sign in or sign up before continuing.'}
    response.body.should  eql(error.to_json)
  end

end  

Two points of differents:

  • Rake::Test::Methods could query the url "/api/v1/xxxx", but ActionController::TestCase::Behavior only execute actions within current controller scope.
  • the reponse in Rake::Test::Methods called: last_response, in ActionController::TestCase::Behavior called: response.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment