首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于Sinatra的Rspec render_template等价物?

用于Sinatra的Rspec render_template等价物?
EN

Stack Overflow用户
提问于 2012-12-25 07:10:50
回答 1查看 718关注 0票数 1

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

代码语言:javascript
运行
复制
response.should render_template('template-name')

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-25 21:35:36

有一些docs on using Rack Test with RSpec here,但这是我设置东西的方式。通过将应用程序包装在模块的类方法中,它可以更容易地在规范中运行,然后只需通过last_response.body验证响应(这是对您的问题的简短回答)。

代码语言:javascript
运行
复制
# 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

代码语言:javascript
运行
复制
# app/config.rb
require 'main'

module HelloWorld
  def self.app
    Rack::Builder.app do
      # middleware setup here, cookies etc
      run App
    end
  end
end

代码语言:javascript
运行
复制
# app/main.rb
require 'sinatra/base'

module HelloWorld
  class App < Sinatra::Base
    get "/", :provides => :json do
      {key: "value"}.to_json
    end
  end
end

代码语言:javascript
运行
复制
# 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

代码语言:javascript
运行
复制
# 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

代码语言:javascript
运行
复制
# 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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14026390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档