rspec-grapeでのGrape APIのテストコード
Grape APIのRSpecについて調べてみると、大体 Request Spec での書き方ばかりだったので備忘録的なメモとして。
使用するGemは下記
大体はREADME読めば分かるんだけど、書き方としては以下のように type: :api
を定義する。
describe API::V1::Users, type: :api do ... end
テスト対象のAPIはcontextで指定する。
contextの記載は下記のように METHOD PATH
の形で指定する。
なので、POSTメソッドのテストの場合は POST /api/v1/users/
のように記載する。
describe API::V1::Users, type: :api do context "GET /api/v1/users" do .... end end
type requestとは違い、リクエストには call_api
メソッドを使用する。
引数にhash形式でパラメータを渡す事が出来る。
describe API::V1::Users, type: :api do context "GET /api/v1/users" do it "request success" do expect(call_api.status).to eq 200 end end # パラメータが必要な場合 context "POST /api/v1/users/create" do it "request success" do expect(call_api({name: "hoge"}).status).to eq 200 end end end
また、PATHにid等の可変パラメータがある場合は下記のように指定する。
可変パラメータはcontextで記載した :id
などの値を call_api
にhashで渡す事で反映される。
describe API::V1::Users, type: :api do context "GET /api/v1/users/:id" do it "request success" do expect(call_api({id: 1}).status).to eq 200 end end end
以下調査中。
Authorization等、認証でheaderに値を設定する必要がある場合の call_api
の呼び方。
type requestと同様に引数で渡せばいい?