Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Testing JSON API with functional tests

I have just a simple question, but I could not found any answer.

My ruby on rails 3.2.2 appilcation have a JSON API with a devise session authentication.

My question is: How can I test this API with functional or integration tests - and is there a way to handle a session?

I do not have a front end, just a API that I can do GET. POST. PUT. and DELETE with JSON Body.

Which is the best way to test this automated?

EXAMPLE create new user

POST www.exmaple.com/users

{
 "user":{
    "email" : "[email protected]",
    "password " : "mypass"
  }
}
like image 605
Lailo Avatar asked May 23 '12 13:05

Lailo


People also ask

How do you run a Minitest in rails?

To run a Minitest test, the only setup you really need is to require the autorun file at the beginning of a test file: require 'minitest/autorun' . This is good if you'd like to keep the code small. A better way to get started with Minitest is to have Bundler create a template project for you.

What is Rails integration test?

While unit tests make sure that individual parts of your application work, integration tests are used to test that different parts of your application work together.


1 Answers

It is easy to do with functional tests. In a user example I would put them in spec/controllers/users_controller_spec.rb in Rspec:

 require 'spec_helper'

 describe UsersController do
   render_views # if you have RABL views

   before do
     @user_attributes = { email: "[email protected]", password: "mypass" }
   end

   describe "POST to create" do

     it "should change the number of users" do
        lambda do
          post :create, user: @user_attributes
        end.should change(User, :count).by(1)
     end

     it "should be successful" do
       post :create, user: @user_attributes
       response.should be_success
     end

     it "should set @user" do
       post :create, user: @user_attributes
       assigns(:user).email.should == @user_attributes[:email]
     end

     it "should return created user in json" do # depend on what you return in action
       post :create, user: @user_attributes
       body = JSON.parse(response.body)
       body["email"].should == @user_attributes[:email]
      end
  end

Obviously, you can optimize specs above, but this should get you started. Cheers.

like image 92
Simon Bagreev Avatar answered Sep 22 '22 09:09

Simon Bagreev