it
ブロックを通常の方法でブロックするのが好きではないので、私は少し違った構成にしていますが、使用したコードは問題ありません。システムの複数の側面のテストが奨励されると思います時:それは(それをやっていないため、あなたに称賛)before
ブロック内のインスタンス変数よりはましだから
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を使用しました。 post
はbefore
ブロックに含まれています。これは実際には仕様の一部ではありませんが、あなたの仕様に先立って発生する副作用です。 subject
は応答であり、it
は簡単な呼び出しになります。
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
をして、そのように呼び出します:応答をチェックすることokですので
ので、多くの場合、私はにそれを置く必要がある
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.configure do |config|
config.include Helpers, :type => :request
その後:RSpecのコンフィグを経由して、それを含めることによって、
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
ビットを書き込んだ後、私はit would be more helpful as a gemを実現。
あなたがこれを見ましたか? http://stackoverflow.com/questions/5159882/how-to-check-for-a-json-response-using-rspec/5161898#5161898 – zetetic