我已经在谷歌上搜索了大约90分钟,仍然没有答案。我在哪里设置default_url_options?我已经设置了config.action_mailer.default_url_options来解决其他地方的这个错误,但现在我在尝试使用RSpec规范内的URL helper时得到了这个错误。我不知道它在哪里期望default_url_options被设置。

 Failure/Error: listing_url(listing).should match(/\/\d+-\w+$/)
 RuntimeError:
   Missing host to link to! Please provide :host parameter or set default_url_options[:host]
 # ./spec/routing/listing_routing_spec.rb:9:in `block (3 levels) in <top (required)>'

这段代码与电子邮件/ActionMailer无关,它只是需要一个URL而不是路径。

什么好主意吗?


当前回答

Rails.application.routes.default_url_options(主持人):= ' localhost: 3000

在发展中。Rb / test。Rb,可以更简洁如下:

Rails.application.configure do
  # ... other config ...

  routes.default_url_options[:host] = 'localhost:3000'
end

其他回答

Rails.application.routes.default_url_options(主持人):= ' localhost: 3000

在发展中。Rb / test。Rb,可以更简洁如下:

Rails.application.configure do
  # ... other config ...

  routes.default_url_options[:host] = 'localhost:3000'
end
Your::Application.routes.draw do
  default_url_options :host => "example.com"

  # ... snip ...
end

在路上的某个地方。rb:)

你可以把host作为参数传递给URL helper:

listing_url(listing, host: request.host)

我也犯了同样的错误。我正确地编写了所有内容,包括教程中的清单10.13。

Rails.application.configure do
.
.
.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delevery_method :test
host = 'example.com'
config.action_mailer.default_url_options = { host: host }
.
.
.
end

显然,把"example.com"换成了我的服务器url。

我在教程中忽略的是这一行:

重新启动开发服务器以激活配置…

所以对我来说,答案是关闭服务器,然后重新打开。

主机应该在每个环境的配置文件中指定。例如:

config/environments/development.rb

看看这个问题和这个问题。