使用したコードは問題ありませんがit
、通常のようにブロックを使用するのは好きではないため、構造は少し異なりますが、一度にシステムの複数の側面をテストすることをお勧めします。
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
subject { last_response }
it { should be_ok }
ブロック内のインスタンス変数よりも優れているため、letを使用しました(これを行わないことをお勧めします)。before
これpost
は実際には仕様の一部ではないため、before
ブロック内にありますが、仕様を設定する前に発生する副作用です。これsubject
が応答でありit
、単純な呼び出しを行います。
応答をチェックする必要があるので、頻繁に共有の例に入れます:
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
そしてそれをそのように呼びます:
describe "Creating a new channel" do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
it_should_behave_like "Any route"
# now spec some other, more complicated stuff…
subject { JSON.parse(last_response.body) }
it { should == "" }
コンテンツタイプは頻繁に変更されるため、ヘルパーに追加します。
module Helpers
def env( *methods )
methods.each_with_object({}) do |meth, obj|
obj.merge! __send__(meth)
end
end
def accepts_html
{"HTTP_ACCEPT" => "text/html" }
end
def accepts_json
{"HTTP_ACCEPT" => "application/json" }
end
def via_xhr
{"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
end
RSpec構成を介して含めることにより、必要な場所にこれを簡単に追加できます。
RSpec.configure do |config|
config.include Helpers, :type => :request
それから:
describe "Creating a new channel", :type => :request do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, env(:accepts_json)
end
そうは言っても、個人的には、JSONを使用して投稿することはありません。HTTP POSTは処理が簡単で、すべてのフォームとjavascriptライブラリが簡単かつ適切に処理します。必ずJSONで応答しますが、JSONを投稿しないでください。HTTPの方がはるかに簡単です。
編集:Helpers
上記のビットを書き留めた後、私はそれが宝石としてより役立つだろうことに気づきました。