ruby 如何在Sinatra中运行测试?

mbjcgjjk  于 12个月前  发布在  Ruby
关注(0)|答案(4)|浏览(156)

我不知道如何测试我的Sinatra应用程序。
Ruby
这似乎不起作用。所有的文件都只谈论如何写文件的内容,而不是如何让它运行。
谢谢

jum4pzuy

jum4pzuy1#

应该够简单了。
给定my_app.rb:

require 'rubygems' # Required only for Ruby version prior to 1.9
require 'sinatra'

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

字符串
和我的应用测试.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:

gem install sinatra rake rack-test


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

ruby my_app.rb
ruby my_app_test.rb

6za6bjd0

6za6bjd02#

我发布了一个基于psyho's answersmall example。我还添加了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

6ss1mwsb

6ss1mwsb3#

下面是一个使用Minitest编写的Sinatra应用程序和集成(或端到端)测试的示例:
app.rb

# frozen_string_literal: true

require 'sinatra'

get '/' do
  'test'
end

字符串
test/integration_test.rb

# frozen_string_literal: true

ENV['APP_ENV'] = 'test'

require 'minitest/autorun'
require 'rack/test'
require 'app'

class IntegrationTest < Minitest::Test
  include Rack::Test::Methods

  def test_request_succeeds
    get '/'
    assert last_response.ok?
    assert_equal 'test', last_response.body
  end

  private

  def app
    Sinatra::Application
  end
end


运行测试configure the test rake task和运行rake test

vm0i2vca

vm0i2vca4#

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

相关问题