Rails – 使用function测试测试JSON API
我只有一个简单的问题,但我找不到任何答案。
我的ruby on rails 3.2.2 appilcation有一个带有设计会话认证的JSON API。
我的问题是: 我如何通过function测试或集成测试来测试这个API – 有没有办法处理会话?
我没有前端,只有我可以做的API GET。 POST。 放。 并使用JSON Body进行删除。
哪种测试方法是自动化的最佳方法?
示例创建新用户
发布www.exmaple.com/users
{ "user":{ "email" : "test@example.com", "password " : "mypass" } }
function测试很容易。 在用户示例中,我将它们放在spec/controllers/users_controller_spec.rb
中的spec/controllers/users_controller_spec.rb
中:
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
显然,你可以优化上面的规格,但这应该让你开始。 干杯。
看看Anthony Eden的演讲“使用Ruby和Cucumber构建和测试API”
您可以使用Cucumber(BDD)来测试此类情况,例如:
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"} ] """
然后,你只需要编写你的步骤,其中pickle gem非常有用