RSpecとCucumberでJSONデータをテストする
collectiveidea/json_spec · GitHub を利用します
Rspecの場合の使用例
describe User do let(:user){ User.create!(first_name: "Steve", last_name: "Richert") } context "#to_json" do it "includes names" do names = %({"first_name":"Steve","last_name":"Richert"}) user.to_json.should be_json_eql(names).excluding("friends") end it "includes the ID" do user.to_json.should have_json_path("id") user.to_json.should have_json_type(Integer).at_path("id") end it "includes friends" do user.to_json.should have_json_size(0).at_path("friends") friend = User.create!(first_name: "Catie", last_name: "Richert") user.friends << friend user.to_json.should have_json_size(1).at_path("friends") user.to_json.should include_json(friend.to_json) end end end
Cucumberの場合の使用例
Feature: User API Background: Given the following users exist: | id | first_name | last_name | | 1 | Steve | Richert | | 2 | Catie | Richert | And "Steve Richert" is friends with "Catie Richert" Scenario: Index action When I visit "/users.json" Then the JSON response should have 2 users And the JSON response at "0/id" should be 1 And the JSON response at "1/id" should be 2 Scenario: Show action When I visit "/users/1.json" Then the JSON response at "first_name" should be "Steve" And the JSON response at "last_name" should be "Richert" And the JSON response should have "created_at" And the JSON response at "created_at" should be a string And the JSON response at "friends" should be: """ [ { "id": 2, "first_name": "Catie", "last_name": "Richert" } ] """
JSONデータをテストしたい場合は、ぜひ活用したいですね。