我有一个接受JSON的post方法:
post '/channel/create' do
content_type :json
@data = JSON.parse(env['rack.input'].gets)
if @data.nil? or !@data.has_key?('api_key')
status 400
body({ :error => "JSON corrupt" }.to_json)
else
status 200
body({ :error => "Channel created" }.to_json)
end
Run Code Online (Sandbox Code Playgroud)
作为rspec的新手,我很困惑,试图找出如何使用可接受的JSON有效负载编写针对该POST的测试.我最接近的是这是非常不准确但我似乎没有问谷歌上帝正确的问题,以帮助我在这里.
it "accepts create channel" do
h = {'Content-Type' => 'application/json'}
body = { :key => "abcdef" }.to_json
post '/channel/create', body, h
last_response.should be_ok
end
Run Code Online (Sandbox Code Playgroud)
在Sinatra中测试API的任何最佳实践指南也将非常受欢迎.
iai*_*ain 11
您使用的代码很好,虽然我的结构略有不同,因为我不喜欢像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 }
Run Code Online (Sandbox Code Playgroud)
我已经使用了let,因为它比before块中的实例变量更好(不赞成你这样做).这post是一个before块,因为它不是规范的一部分,而是在您所指定的之前发生的副作用.这subject是响应,这使得it一个简单的调用.
因为需要检查响应是否正常所以我经常把它放在一个共享示例中:
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
Run Code Online (Sandbox Code Playgroud)
然后将其称为:
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 == "" }
Run Code Online (Sandbox Code Playgroud)
因为内容类型经常变化,所以我把它放在帮助器中:
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
Run Code Online (Sandbox Code Playgroud)
通过RSpec配置将其添加到需要的地方很容易:
RSpec.configure do |config|
config.include Helpers, :type => :request
Run Code Online (Sandbox Code Playgroud)
然后:
describe "Creating a new channel", :type => :request do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, env(:accepts_json)
end
Run Code Online (Sandbox Code Playgroud)
说了这么多,就个人而言,我不会发布使用JSON.HTTP POST易于处理,每个表单和JavaScript库都可以轻松完成.通过各种方式响应JSON,但不发布JSON,HTTP更容易.
编辑:在写完Helpers上面的内容后,我意识到它作为一个宝石会更有帮助.
| 归档时间: |
|
| 查看次数: |
6496 次 |
| 最近记录: |