[~/rack/rack-rspec(master)]$ tree . |--- Gemfile |--- Gemfile.lock |--- README |--- Rakefile |--- lib | |--- rsack | | `--- server.rb | `--- rsack.rb `--- spec |--- rsack | `--- server_spec.rb `--- spec_helper.rb 4 directories, 8 files
[~/rack/rack-rspec(master)]$ cat lib/rsack.rb require 'rack' require 'rsack/server'
[~/rack/rack-rspec(master)]$ cat lib/rsack/server.rb module Rsack class Server def call(env) #["200", {}, "hello"] response = Rack::Response.new response.write("Hello world!") response.finish end end end
[~/rack/rack-rspec(master)]$ cat spec/rsack/server_spec.rb require 'spec_helper' describe Rsack::Server do #let(:server) { Rack::MockRequest.new(Rsack::Server.new) } def server Rack::MockRequest.new(Rsack::Server.new) end context '/' do it "should return a 200 code" do response = server.get('/') response.status.should == 200 end end endRack::MockRequest helps testing your Rack application without actually using HTTP.
Rack::MockRequest.new(Rsack::Server.new)After performing a request on a URL
response = server.get('/')
with get/post/put/patch/delete
, it
returns a
MockResponse
with useful helper methods for effective
testing (Véase el código de MockResponse en Github en el fichero
lib/rack/mock.rb).
Un objeto MockResponse dispone de los métodos:
=~ [] match newy de los atributos:
body [R] Body errors [RW] Errors headers [R] Headers original_headers [R] Headers status [R] Status
Si se usan middleware adicionales es necesario especificarlo en server
. Por ejemplo:
Rack::MockRequest.new(Rack::Session::Cookie.new(RockPaperScissors::App.new, :secret =>'cookie'))
[~/rack/rack-rspec(master)]$ cat spec/spec_helper.rb $:.unshift File.expand_path(File.dirname(__FILE__)+'../lib') $:.unshift File.dirname(__FILE__) #puts $:.inspect require 'rspec' require 'rack' require 'rsack'
[~/rack/rack-rspec(master)]$ cat Rakefile desc "run rspec tests" task :default do sh "rspec spec/rsack/server_spec.rb" end
[~/rack/rack-rspec(master)]$ cat Gemfile # A sample Gemfile source "https://rubygems.org" gem 'rack' group :development, :test do gem 'rspec' end
Casiano Rodriguez León 2015-01-07