grape apiユニットテスト

3767 ワード

2つのサイトをお勧めします.
https://github.com/rspec/rspec-rails
http://rspec.info/documentation/
apiのユニットテストをアップロードしましたhttps://github.com/shiralwz/grape_api_rspec
主な手順:
(1)Gemfileに新しいgemを入れる
gem 'rspec-rails', '~> 3.0'

(2)Download and install by running
bundle install

(3)Initialize the  spec/  directory (where specs will reside) with
rails generate rspec:install

このコマンドを実行すると、次の3つのファイルが自動的に生成されます..rspec spec/spec_helper.rb spec/rails_helper.rb
(4)新規ユニットテストのコード
(5)実行
bundle exec rspec  spec/...

============================
apiのユニットテストコード
require 'rails_helper'

RSpec.describe "helloAPI",type: :request do
  describe "GET the /api/hello" do
    it 'should return correct response via GET' do
      get '/api/hello', name: 'Mike'
      expect(response).to be_success
      expect(response).to have_http_status(200)
      body = JSON.parse(response.body)
      body['message'] == 'Hello Mike via GET'
    end 
  end 

  describe "POST the /api/hello" do
    it 'should return correct response via POST' do
      post '/api/hello', name: 'Mike'
      expect(response).to be_success
      expect(response).to have_http_status(200) //     api    200    200,   201
      body = JSON.parse(response.body)
      body['message'] == 'Hello Mike via POST'
    end 
  end 
end