35
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RspecでJsonをテストするMatcher

Last updated at Posted at 2013-01-28

RailsでAPIを作成した際のテストに使えるMatcherです.
下記のようにJsonデータのテストを書くことができます.

/rspec/controller/test_controller_spec.rb
# レスポンスに{"result" => {"2000" => {"03" => {"TestData" => x}}}}が存在することをテスト
subject { JSON.parse(response.body) }
it{ should have_json("/result/2000/03/TestData") }

以下のようにmatcherを定義します.

/rspec/support/controller_helper.rb
# spec/support/custom_matchers.rb
  RSpec::Matchers.define :have_json do |selector|
    match do |response_body|
      selector.split('/')[1..-1].inject(response_body) do |body, address|
        body[address]
      end
      true
    end

    failure_message_for_should do |actual|
      "json_data should have path(#{selector})"
    end
  end

追記

json_specというgemがあるんですね。
折角なので、json_specでの記述例を挙げておきます。

/rspec/controller/test_controller_spec.rb
subject { response.body }
# レスポンスに{"result" => {"2000" => {"03" => {"TestData" => x}}}}が存在する
it{ should have_json_path("result/2000/03/TestData") }
# レスポンスに{"result" => {"2000" => {"03" => {"TestData" => x}}}}のxがInteger
it{ should have_json_type(Integer).at_path("result/2000/03/TestData") }
# レスポンスに{"result" => {"2000" => {"03" => {"TestData" => 0}}}}が存在する
it{ should be_json_eql(0).at_path("result/2000/03/TestData") }
35
33
2

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
35
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?