我只有一个简单的问题,但我找不到任何答案。
我的 Ruby on rails 3.2.2 应用程序有一个带有设计会话身份验证的 JSON API。
我的问题是:如何使用功能或集成测试来测试此 API - 有没有办法处理会话?
我没有前端,只有一个我可以做的 API。 发布。 并删除 JSON 正文。
哪种方法是测试这种自动化的最佳方法?
例 创建新用户
发布 www.exmaple.com/users
{
"user":{
"email" : "test@example.com",
"password " : "mypass"
}
}
使用功能测试很容易做到。在用户示例中,我会将它们放在 Rspec 的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"}
]
"""
然后,你只需要写下你的步骤,泡菜宝石会非常有用