Skip to content

Instantly share code, notes, and snippets.

@JunichiIto
Last active June 15, 2019 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JunichiIto/4e17b9e80a3842deab42916cef827cf1 to your computer and use it in GitHub Desktop.
Save JunichiIto/4e17b9e80a3842deab42916cef827cf1 to your computer and use it in GitHub Desktop.

ppメソッドでJSON.parse(response.body)の中身を確認してみました。

require 'rails_helper'

describe 'Projects API', type: :request do
  it 'loads a project' do
    user = FactoryBot.create(:user)
    FactoryBot.create(:project, name: "Sample Project")
    FactoryBot.create(:project, name: "Second Sample Project", owner: user)

    get api_projects_path, params: {
      user_email: user.email,
      user_token: user.authentication_token
    }

    expect(response).to have_http_status(:success)
    json = JSON.parse(response.body)
    expect(json.length).to eq 1
    project_id = json[0]["id"]

    get api_project_path(project_id), params: {
      user_email: user.email,
      user_token: user.authentication_token
    }

    expect(response).to have_http_status(:success)
    require 'pp'
    json = pp JSON.parse(response.body)
    expect(json["name"]).to eq "Second Sample Project"
    # Etc.
  end

  it 'creates a project' do
    user = FactoryBot.create(:user)
    FactoryBot.create(:project, name: "Sample Project")
    FactoryBot.create(:project, name: "Second Sample Project", owner: user)

    project_attributes = FactoryBot.attributes_for(:project)

    expect {
      post api_projects_path, params: {
        user_email: user.email,
        user_token: user.authentication_token,
        project: project_attributes
      }
    }.to change(user.projects, :count).by(1)

    expect(response).to have_http_status(:success)
  end
end

実行結果は以下のとおりでした。

$ bundle exec rspec spec/requests/projects_api_spec.rb:4
Run options: include {:locations=>{"./spec/requests/projects_api_spec.rb"=>[4]}}

Projects API
{"id"=>2,
 "name"=>"Second Sample Project",
 "description"=>"A test project.",
 "due_on"=>"2019-01-09",
 "created_at"=>"2019-01-02T10:49:18.495Z",
 "updated_at"=>"2019-01-02T10:49:18.495Z",
 "user_id"=>1,
 "completed"=>nil}
  loads a project

Finished in 0.38077 seconds (files took 2.62 seconds to load)
1 example, 0 failures

上記の結果を見る限り、配列ではなくハッシュが返ってきているので、[0]を付ける必要はないと思われます。

もう少し詳しく言うと、api_project_path(project_id)は指定したproject_idのProjectを返すAPIなので、配列は返ってこないはずです。 (一方、その上に出てくるapi_projects_pathはProjectの一覧を返すので、戻り値が配列になります)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment