Rails - 使用功能测试测试 JSON API [英] Rails - Testing JSON API with functional tests
问题描述
我只有一个简单的问题,但我找不到任何答案.
I have just a simple question, but I could not found any answer.
我的 ruby on rails 3.2.2 应用程序有一个带有设计会话身份验证的 JSON API.
My ruby on rails 3.2.2 appilcation have a JSON API with a devise session authentication.
我的问题是:如何使用功能或集成测试来测试此 API - 是否有处理会话的方法?
我没有前端,只有一个可以 GET 的 API.邮政.放.并使用 JSON 正文删除.
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?
示例创建新用户
发布 www.exmaple.com/users
POST www.exmaple.com/users
{
"user":{
"email" : "test@example.com",
"password " : "mypass"
}
}
推荐答案
使用功能测试很容易.在用户示例中,我会将它们放在 Rspec 中的 spec/controllers/users_controller_spec.rb
中:
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.
这篇关于Rails - 使用功能测试测试 JSON API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!