2012-06-20 173 views
0

我想知道測試REST API的最佳實踐(在這種情況下,使用Sinatra和Rspec)。顯而易見的問題是,如果您有一個測試用於檢查用戶列表GET /users,那麼您需要經歷創建用戶,運行測試,然後銷燬用戶的階段。但是,如果創建/銷燬步驟也取決於API,那麼最終可能會違反基於排序的測試規則,或者在一次測試中測試多個事件(例如,是否添加了用戶?.. GET /users是否會返回用戶列表?..是否刪除了用戶?)。測試Sinatra REST API方法

回答

0

您可以使用FactoryGirl。在您的測試中,您可以通過API創建用戶,或使用FG創建存根,然後刪除,修改等等。 FG是一個非常靈活的ORM測試助手,適用於這類工作。

0

我也同意@three--使用FactoryGirl

爲例(首先,定義採樣對象):

FactoryGirl.define do 

    sequence(:random_ranking) do |n| 
     @random_rankings ||= (1..10000).to_a.shuffle 
     @random_rankings[n] 
    end 

    factory :todo do 
     title { Faker::Lorem.sentence} 
     id { FactoryGirl.generate(:random_ranking) } 
     completed [true, false].sample 
     completed_at Time.new 
     created_at Time.new 
     updated_at Time.new 
    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