你如何在Sinatra进行测试?

时间:2010-01-13 10:27:50

标签: ruby testing sinatra

我不知道如何测试我的Sinatra应用程序。我只是跑

红宝石

这似乎不起作用。那里的所有文件只讨论如何编写文件的内容,而不是如何让它运行。

由于

3 个答案:

答案 0 :(得分:27)

应该够简单。

鉴于my_app.rb:

require 'rubygems'
require 'sinatra'

get '/hi' do
  "Hello World!"
end

和my_app_test.rb:

require 'my_app'
require 'test/unit'
require 'rack/test'

set :environment, :test

class MyAppTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def test_hi_returns_hello_world
    get '/hi'
    assert last_response.ok?
    assert_equal 'Hello World!', last_response.body
  end
end

你应该确保安装了正确的宝石:

gem install sinatra rake rack-test

现在您可以像这样运行您的应用程序和测试:

ruby my_app.rb
ruby my_app_test.rb

答案 1 :(得分:0)

我根据small example发布了psyho's answer。我还添加了ActiveRecord支持,包括测试装置。

我配置了rake来运行测试:

# Rakefile
require_relative './app'
require 'rake'
require 'rake/testtask'
require 'sinatra/activerecord/rake'

Rake::TestTask.new do |t|
  t.pattern = "test/**/*_test.rb"
end

task default: :test

现在我可以运行这样的测试:

rake

示例测试如下所示:

require_relative '../test_helper'

class BlogTest < ActiveSupport::TestCase
  fixtures :blogs

  def test_create
    blog = Blog.create(:name => "Rob's Writing")
    assert_equal "Rob's Writing", blog.name
  end

  def test_find
    blog = Blog.find_by_name("Jimmy's Jottings")
    assert_equal "Stuff Jimmy says", blog.tagline
  end
end

我在每个测试文件中都需要这个帮助程序来连接所有内容:

# test_helper.rb
require_relative '../app'
require 'minitest/autorun'
require 'active_record'
require 'rack/test'

ActiveRecord::Base.establish_connection(:test)

#Set up fixtures and such
class ActiveSupport::TestCase
  include ActiveRecord::TestFixtures
  include ActiveRecord::TestFixtures::ClassMethods
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  self.fixture_path = 'test/fixtures'
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
end

答案 2 :(得分:-1)

应该像ruby your_app_name.rb一样简单。实际上,这显示在Sinatra homepage(底部)。