【发布时间】:2018-11-03 22:40:23
【问题描述】:
我有一个使用devise :confirmable 的User 类,它在创建用户时触发包含确认链接的电子邮件发送。这在development 和production 中完美运行,但在test 环境(Minitest / Capybara)中失败。具体来说,点击确认链接会生成**Forbidden** You don't have permission to access /users/confirmation on this server。
截图:
Forbidden You don't have permission to access /users/confirmation on this server
奇怪的是,当我从 rails console 创建用户时,就像我在集成测试中所做的那样,它可以工作。那么,为什么在test 环境下会失败呢?
测试:
u = FactoryBot.create(:user)
email = ActionMailer::Base.deliveries.last
plain_part = email.multipart? ? (email.text_part ? email.text_part.body.decoded : nil) : email.body.decoded
confirmation_link = plain_part[/<a href="(http:\/\/.*)">Confirm my account<\/a>/,1]
puts "--- #{confirmation_link} ---" # visual check of extracted URL
visit confirmation_link # Forbidden You don't have permission...
save_and_open_screenshot # saves to tmp/capybara/capybara-*.png
在控制台:
require 'factory_bot'
# factory creation code omitted from here
u = FactoryBot.create(:user)
# produces and renders link
这种确认链接在除test之外的所有环境中都是这样的:
http://localhost:3000/users/confirmation?confirmation_token=TxYdRmVzcuPE7PAx7yJh
...在test 中,它们看起来像这样:
http://localhost/users/confirmation?confirmation_token=NqyaVL5EKEnz46zMzDQs
(test 中未指定端口。)
我在这些集成测试中使用Rails 5.2.0 和Capybara 驱动程序selenium_chrome_headless。
【问题讨论】:
-
您使用的是什么版本的 Rails,以及您在 Capybara 中使用的驱动程序?另外 - 确认链接将指向端口 3000 - 您实际上是在端口 3000 上运行您的测试服务器吗?通常是开发服务器
-
哇!非常感谢。你的想法是对的……它与端口有关!通过将
Capybara.server_port = '3000'添加到test/test_helper.rb,并通过confirmation_link.gsub!(/localhost/,"localhost:#{Capybara.server_port}")修改(在集成测试中)电子邮件生成的URL,它立即起作用。后者感觉不是一个长期的解决方案,因为猴子补丁似乎很脆弱,但它确实证实了这个问题。理想情况下,生成的 URL 将使用提供的端口号。也许您可以在这方面提出建议?无论哪种方式,请提供答案,我会接受! -
...或者也许有一种不同且更好的方法来执行此操作...例如以某种方式获取生成的 URL 以包含当前端口号(因为我看到它随着每次测试运行而变化。 .. 例如
Listening on tcp://127.0.0.1:60770、Listening on tcp://127.0.0.1:60127、Listening on tcp://127.0.0.1:58623)。
标签: ruby-on-rails capybara factory-bot minitest