Rails - Testing JSON API with functional tests

自作多情 提交于 2019-12-31 10:05:47

问题


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" : "test@example.com",
    "password " : "mypass"
  }
}

回答1:


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: "test@example.com", 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.




回答2:


Have a look at Anthony Eden's talk "Build and Test APIs with Ruby and Cucumber"




回答3:


You can user Cucumber(BDD) to test such cases, for example:

Feature: Successful login
  In order to login
  As a user 
  I want to use my super API

  Scenario: List user
    Given the system knows about the following user:
      | email            | username |
      | test@example.com | blabla   |
    When the user requests POST /users
    Then the response should be JSON:
    """
    [
      {"email": "test@example.com", "username": "blabla"}
    ]
    """

then, you just need to write your steps, where pickle gem 'd be very useful



来源:https://stackoverflow.com/questions/10721225/rails-testing-json-api-with-functional-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!