0
我正在構建一個Sinatra應用程序,目前它將輸出JSON模板作爲API的一部分。當軌道和RSpec的護欄寶石檢測,我能夠撥打:相當於Sinatra的Rspec render_template?
response.should render_template('template-name')
但是因爲我沒有使用Rails的我假設這是行不通的。有什麼替代品用於Sinatra測試json輸出?謝謝!
我正在構建一個Sinatra應用程序,目前它將輸出JSON模板作爲API的一部分。當軌道和RSpec的護欄寶石檢測,我能夠撥打:相當於Sinatra的Rspec render_template?
response.should render_template('template-name')
但是因爲我沒有使用Rails的我假設這是行不通的。有什麼替代品用於Sinatra測試json輸出?謝謝!
有一些docs on using Rack Test with RSpec here,但這是我如何設置我的東西了。通過將應用程序包裝在模塊的類方法中,它使得在規範中運行起來更容易,然後通過last_response.body
(這是對您的問題的簡短回答)驗證響應。
# config.ru
require 'rubygems'
require "bundler/setup"
root = File.expand_path File.dirname(__FILE__)
require File.join(root , "./app/config.rb")
# everything was moved into a separate module/file
# to make it easier to set up tests
map "/" do
run HelloWorld.app
end
# app/config.rb
require 'main'
module HelloWorld
def self.app
Rack::Builder.app do
# middleware setup here, cookies etc
run App
end
end
end
# app/main.rb
require 'sinatra/base'
module HelloWorld
class App < Sinatra::Base
get "/", :provides => :json do
{key: "value"}.to_json
end
end
end
# spec/spec_helper.rb
require 'rspec'
Spec_dir = File.expand_path(File.dirname __FILE__)
require 'rack/test'
Dir[ File.join(Spec_dir, "/support/**/*.rb")].each do |f|
require f
end
# spec/support/shared/all_routes.rb
require 'hello_world' # <-- your sinatra app
shared_context "All routes" do
include Rack::Test::Methods
let(:app){
HelloWorld.app
}
end
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
# spec/hello_world_spec.rb
require 'spec_helper'
describe 'getting some JSON' do
include_context "All pages"
let(:expected) {
'{"key": "value"}'
}
before do
get '/', {}, {"HTTP_ACCEPT" => "application/json" }
end
it_should_behave_like "Any route"
subject { last_response.body }
it { should == expected }
end