リア充爆発日記

You don't even know what ria-ju really is.

Rails3+rspec2でWeb APIサーバのpostをテストする方法がよくわからなかった件

RESTful APIとWebサイトを1つのアプリケーションで作るの続き。

最初にテスト書こうと思ってintegration_testから攻めようと思ったらpostが発行できない。(か、もしくはする方法がわからない)

けっこうな時間を調査に費やした結果、postを発行しようと思ったらcontrollerのテストとして書かないとダメっぽい。rspecはテストクラスが配置されているディレクトリも見ているそうな。

リクエストの発行からレスポンスの受取まで一気通貫したテストを書きたいので、controllerのテストでいいのか?という気持ちはあったけど、もうわかんないからそれでいいや、いつか誰か何が間違ってるのか教えてくれるだろ。

spec/controllers/v1/users_controller_spec.rb

require 'spec_helper'

describe V1::UsersController do

  describe "GET" do
    let(:user) { FactoryGirl.create(:user) }

    it "should respond with json" do
      get :show, id: user.id
      parsed_body = JSON.parse(response.body)
      parsed_body["name"].should == user.name
    end
  end

  describe "POST" do
    describe "with valid data" do
      it "should return status 201 and user.id" do
        params = FactoryGirl.attributes_for(:user)
        post :create, user: params

        @response.status.should be(201)
        parsed_body = JSON.parse(@response.body)
        parsed_body["id"].should be_a_kind_of(Numeric)
      end
    end

    describe "with invalid data" do
      it "should return error messages" do
        params = FactoryGirl.attributes_for(:user)
        params["name"] = ""

        post :create, user: params

        @response.status.should be(422)
        parsed_body = JSON.parse(@response.body)
        parsed_body["errors"].should_not be_nil
      end
    end
  end
end

うまくいったときとバリデーションに引っかかった時をテストしてます。

users_controller.rb

  def show
    @user = User.find(params[:id])
    respond_with @user
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      respond_with @user, location: nil
    else
      respond_with @user
    end

  end

"respond_with @user, location: nil"となっているのは、RESTの基本的な考え方として、get以外のリクエストに対しては次の行き先を返そうぜ!というのがあるらしくて、でも、いらないからnilにしてあるんだけど何かモヤッとするな。。railsを使っているときにconventionに逆らうと天罰が下ることが多いからな・・・。

鋼の錬金術師 (1) (ガンガンコミックス)

鋼の錬金術師 (1) (ガンガンコミックス)

鋼の錬金術師全27巻 完結セット (ガンガンコミックス)

鋼の錬金術師全27巻 完結セット (ガンガンコミックス)