LoginSignup
24
19

More than 5 years have passed since last update.

【RSpec】APIのRSpecの書き方 for 初心者

Last updated at Posted at 2015-06-26

○テストケース

基本は200 successをチェックします。
jsonの値をチェックしたり、モデルの増減を調べたりしますが、それは他のサイトで何を書くべきか調べてください。

it "200 success" do
  get url, params 
  expect(response).to have_http_status 200
end

普通のrspecと同じですね。
getで、paramsと一緒にurlを叩くとうまくいきます。
という流れです。

○全体の流れ

Rspec.describe InternalApi::Books, type: :request do
  describe 'GET /books/show' do 
    let(:url) { "/internal/books/show" }
    let(:book) { create(:book, title: 'ノルウェイの森', author: '村上春樹') }
    let(:params) do
        {
            id: book.id,
            access_token: "aaaaaaaaaaaaa" 
        }
    end

    # "do {} end == {{}}" 中の{}はハッシュです。紛らわしいですが。
    # ここまででurlとparamsを作成しました。

    it "200 success" do
      get url, params
      expect(response).to have_http_status 200
    end

    # urlとparamsをgetメソッドに渡すと成功します。

○コツ

この形さえ抑えてしまえば、テストデータを作成することと、マッチャを変更するだけで汎用可能です。

24
19
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
19