Rspec render_template相当于Sinatra?

时间:2012-12-24 23:10:50

标签: rspec sinatra rspec-rails

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

response.should render_template('template-name')

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

1 个答案:

答案 0 :(得分:-1)

有一些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