您使用的代码很好,虽然我的结构会略有不同,因为我不喜欢像您通常看到的那样使用 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 example:
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 位后,我意识到it would be more helpful as a gem。