gpt4 book ai didi

ruby - Sinatra 发布请求时出现无效的 URI 错误

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:08 24 4
gpt4 key购买 nike

作为 RSpec tutorial 的一部分,我正在研究 Sinatra 演示应用程序(official repo)。该应用程序使用 a la carte 安装 ActiveRecord — 没有 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

环境.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?

最佳答案

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

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

您的应用定义的唯一路由在这里:

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

即使使用 Symbol 作为 url 也不起作用:

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

而且,因为 Symbol 对 rspec 测试中的 url 不起作用,这意味着 Sinatra 接受给 post() 的第一个参数,例如:'/books',并将其与您在 App 类中定义的路由进行比较:

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

if requested_route != defined_route
puts "URI ERROR"
end

--output:--
URI ERROR

关于ruby - Sinatra 发布请求时出现无效的 URI 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com