Back

ruby - sinatra中使用rspec 与 如何单独使用rspec

发布时间: 2019-03-15 10:39:00

参考:http://recipes.sinatrarb.com/p/testing/rspec

Rspec的各种expect 在这里;http://rspec.info/documentation/3.8/rspec-expectations/

非常简单。 特别好用。 

1. 有个app.rb 

require 'sinatra'
require 'sinatra/json'
require 'sinatra/activerecord'

Dir[File.join(__dir__, 'model', '*.rb')].each { |file| require file }

get '/' do
  "Hi there, can I help you ?"
end

2. 有个spec/spec_helper.rb

require 'rack/test'
require 'rspec'

ENV['RACK_ENV'] = 'test'

require File.expand_path '../../app.rb', __FILE__

module RSpecMixin
  include Rack::Test::Methods
  def app() Sinatra::Application end
end

RSpec.configure { |c| 
    c.include RSpecMixin 
    # 为了使用.should 
    c.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
}

3. spec/app_spec.rb

require File.expand_path '../spec_helper.rb', __FILE__

describe "My Sinatra Application" do
  it "应该可以访问欢迎页" do
    get '/'
    # Rspec 2.x
    expect(last_response).to be_ok
  end
end

运行方式: bundle exec rspec spec/app_spec.rb

需要导入数据库结构的话,使用:

1. 生成一个 新的 db/schema.rb (可以通过其他项目的rails 命令来生成, ,或者在sinatra下, $ rake db:schema:dump 

2. 在测试环境下加载这个文件: $ rake db:schema:load APP_ENV=test  (注意这里不是RAILS_ENV) 

单独使用rspec

1. Gemfile:

gem 'rspec'

2. bundle install --binstubs

3. ./bin/rspec --init

就可以了

Back