Sinatra发布请求

时间:2015-10-11 17:00:29

标签: ruby rspec sinatra rack

我正在使用Sinatra演示应用程序作为RSpec tutorialofficial repo)的一部分。该应用程序使用ActiveRecord-no Rails的单点安装。当我在运行规范时尝试将Book对象发布到服务器时,我得到一个 InvalidURIError

Failures:

  1) App creates a book
     Failure/Error: post :books, book: { name: "My first book" }
     URI::InvalidURIError:
       bad URI(is not URI?): books
     # /Users/andrekibbe/.rvm/gems/ruby-2.2.1/gems/rack-test-0.6.3/lib/rack/test.rb:193:in `env_for'
     # /Users/andrekibbe/.rvm/gems/ruby-2.2.1/gems/rack-test-0.6.3/lib/rack/test.rb:66:in `post'
     # ./spec/rack_spec.rb:10:in `block (2 levels) in <top (required)>'

rack_spec.rb

require "environment"
require "rack_app"

fdescribe App do
  include Rack::Test::Methods

  let(:app) { App }

  it "creates a book" do
    post :books, book: { name: "My first book" }

    expect(last_response.status).to eq 201
  end
end

rack_app.rb

class App < Sinatra::Base
  post '/books' do
    book = Book.new params[:book]
    if book.save
      status 201
    else
      status 502
    end
  end
end

spec_helper.rb

require "environment"
require "factory_girl"
require "database_cleaner"
require "rack/test"
require_relative "./factories.rb"

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.include Rack::Test::Methods

  config.before(:suite) do
    begin
      DatabaseCleaner.start
    ensure
      DatabaseCleaner.clean
    end
  end
end

book.rb

class Book < ActiveRecord::Base
  validates_presence_of :name
end

的environment.rb

require "sinatra"
require "active_record"

ActiveRecord::Base.establish_connection(
  adapter: :sqlite3,
  database: File.expand_path("../../db/test.sqlite3", __FILE__)
)

什么是post :books, book: { name: "My first book" }使得Rack将请求视为错误的URI?

1 个答案:

答案 0 :(得分:2)

如果您在评论中进行了我建议的更改,那么您的代码对我有用,但是,如果您在代码中使用了以下内容:

post '/books', book: {...}

或:

post :'/books', ...

...当然那些线路不起作用。 ...表示“与原始代码相同,因为我浪费时间输入”。以下是建议的更改:

<强> rack_app.rb

require "environment"
require "rack_app"

fdescribe App do
  let(:app) { App }

  it "creates a book" do
    post '/books', book: { name: "My brand new book" }
    expect(last_response.status).to eq 201
  end
end

您的App定义的唯一路线是:

class App < Sinatra::Base
  #       +--------This is the only url your App responds to  
  #       |        and ONLY if it is contained in a post request
  #       V
  post '/books' do

    book = Book.new params[:book]

    if book.save
      status 201
    else
      status 502
    end

  end

end

即使使用符号作为网址也不起作用:

  it "creates a book" do
    post :'/books', book: { name: "My brand new book" }

并且,因为符号不适用于你的rspec测试中的url,这意味着Sinatra接受post()给出的第一个参数,例如: :'/books',并将其与您在App类中定义的路线进行比较:

defined_route = '/books'
requested_route = :'/books'

if requested_route != defined_route
  puts "URI ERROR"
end

--output:--
URI ERROR