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に逆らうと天罰が下ることが多いからな・・・。
- 作者: 荒川弘
- 出版社/メーカー: スクウェア・エニックス
- 発売日: 2002/01
- メディア: コミック
- 購入: 3人 クリック: 206回
- この商品を含むブログ (316件) を見る
- 作者: 荒川弘
- 出版社/メーカー: スクウェア・エニックス
- 発売日: 2010/12/15
- メディア: コミック
- 購入: 3人 クリック: 23回
- この商品を含むブログ (4件) を見る
has_oneなmodelとhas_manyなmodelのbuiltが混乱する件につきまして
has_manyの場合はfoo.bars.build()
has_oneの場合はfoo.build_bar()
なんで??