1

我目前正在构建一个 Sinatra 应用程序,它将作为 API 的一部分输出 JSON 模板。在使用 rails 和 rspec-rails gem 进行测试时,我可以调用:

response.should render_template('template-name')

但是,由于我没有使用 Rails,所以我假设这不起作用。Sinatra 用于测试 json 输出的替代方法是什么?谢谢!

4

1 回答 1

-1

这里有一些关于使用 RSpec 和 RSpec 测试的文档,但这就是我设置我的东西的方式。通过将应用程序包装在模块的类方法中,可以更轻松地在规范中运行,然后只需通过验证响应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
于 2012-12-25T13:35:35.993 回答