1. 程式人生 > >Rspec: everyday-rspec實操。第7章使用請求測試-測試API

Rspec: everyday-rspec實操。第7章使用請求測試-測試API

控制 tor 使用 spec rip resp pda mon create

測試應用與非人類用戶的交互,涵蓋外部 API

7.1request test vs feature test

RSpec 來說,這種專門針 對 API 的測試最好放在 spec/requests 目錄中,與前面編寫的功能測試分開。

這種測試也不使用 Capy- bara,因為它模擬的是瀏覽器交互,而不是程序交互。

我們要使用的是前面測試控制器響應的 HTTP 動 詞:getpostdelete patch

end-point:端點。

7.2測試GET請求

請求測試與控制器測試不通的地方在於,它不限定於特定的控 制器,

可以使用應用的任何路由

bin/rails g rspec:request projects_api

create spec/requests/projects_apis_spec.rb

it "loads a project" do user = FactoryGirl.create(:user) FactoryGirl.create(:project, name:"Sample Project") FactoryGirl.create(:project, name:"Second Sample Project", owner: user)
#發送HTTP GET請求,為了驗證身份, API 要求提供用戶的電子郵件地址和驗證令牌,因此我們將其放到參數中 get api_projects_path, params:{ user_email: user.email, user_token: user.authentication_token } expect(response).to have_http_status(:success)

#調試:看看response.body是什麽。一個array,包含了登陸用戶的projects的信息.

[{"id":2,"name":"Second Sample Project","description":"A test project.","due_on":"2018-05-26","created_at":"2018-05-19T07:30:14.169Z","updated_at":"2018-05-19T07:30:14.169Z","user_id":1}]

byebug puts "---#{response.body}---" json = JSON.parse(response.body) puts "---#{json}---" byebug

#調試:轉化為json ,: 變為 =>

[{"id"=>2, "name"=>"Second Sample Project", "description"=>"A test project.", "due_on"=>"2018-05-26", "created_at"=>"2018-05-19T07:30:14.169Z", "updated_at"=>"2018-05-19T07:30:14.169Z", "user_id"=>1}]

expect(json.length).to eq 1 project_id = json[0]["id"] puts "---#{project_id}---" byebug# 期望json的數據是一條,之後獲取這個project的??。用於再次請求API,獲得這個project的詳細信息。 get api_project_path(project_id), params:{ user_email: user.email, user_token: user.authentication_token } expect(response).to have_http_status(:success) json = JSON.parse(response.body) expect(json[‘name‘]).to eq "Second Sample Project"

#最後,解析第二次請求返回的JSON數據。看看是否match.

end

7.3 測試POST請求

Rspec: everyday-rspec實操。第7章使用請求測試-測試API