测试Sinatra REST API方法
我想知道测试RESTAPI的最佳实践(在本例中,使用Sinatra和Rspec)。显而易见的问题是,如果您有一个检查用户列表的测试测试Sinatra REST API方法,api,rest,testing,rspec,sinatra,Api,Rest,Testing,Rspec,Sinatra,我想知道测试RESTAPI的最佳实践(在本例中,使用Sinatra和Rspec)。显而易见的问题是,如果您有一个检查用户列表的测试GET/users,那么您需要经历创建用户、运行测试、然后销毁用户的各个阶段。但是,如果创建/销毁步骤也依赖于API,则最终可能会违反基于顺序的测试规则,或者在一个测试中测试多个内容(例如,它是否添加了用户?。GET/users是否返回用户列表?。它是否删除了用户?。您可以使用FactoryGirl。在测试中,您可以通过API创建用户,或者使用FG创建存根,然后删除、
GET/users
,那么您需要经历创建用户、运行测试、然后销毁用户的各个阶段。但是,如果创建/销毁步骤也依赖于API,则最终可能会违反基于顺序的测试规则,或者在一个测试中测试多个内容(例如,它是否添加了用户?。GET/users
是否返回用户列表?。它是否删除了用户?。您可以使用FactoryGirl。在测试中,您可以通过API创建用户,或者使用FG创建存根,然后删除、修改等等。FG是一个非常灵活的ORM测试助手,对这类东西非常有用。我也同意@three-use
例如(首先,定义示例对象):
在规格测试中,描述您的列表操作:
describe 'GET #index' do
before do
@todos = FactoryGirl.create_list(:todo, 10)
@todos.each do |todo|
todo.should be_valid
end
get :index, :format => :json
end
it 'response should be OK' do
response.status.should eq(200)
end
it 'response should return the same json objects list' do
response_result = JSON.parse(response.body)
# these should do the same
# response_result.should =~ JSON.parse(@todos.to_json)
response_result.should match_array(JSON.parse(@todos.to_json))
end
end
describe 'GET #index' do
before do
@todos = FactoryGirl.create_list(:todo, 10)
@todos.each do |todo|
todo.should be_valid
end
get :index, :format => :json
end
it 'response should be OK' do
response.status.should eq(200)
end
it 'response should return the same json objects list' do
response_result = JSON.parse(response.body)
# these should do the same
# response_result.should =~ JSON.parse(@todos.to_json)
response_result.should match_array(JSON.parse(@todos.to_json))
end
end