【问题标题】:Flashes not showing in test environment在测试环境中不显示闪烁
【发布时间】:2026-01-14 04:35:01
【问题描述】:

我目前正在使用 rspec 编写集成测试。我有问题的测试很简单:

accounts_controller.rb

def create
  @account = Account.new(account_params)
  authorize @account
if @account.save
  flash[:notice] = 'Your account has been successfully created'
  redirect_to :root
else
  render :new
end

sign_up_spec.rb

require 'rails_helper'

feature 'Accounts' do
  scenario 'creating an account' do
    visit root_path
    click_link 'Get Started'
    fill_in 'Name', with: 'Test'
    click_button 'Create account'
    save_and_open_page
    success_message = 'Your account has been successfully created'
    expect(page).to have_content(success_message)
  end
end

问题是,在开发过程中,会出现提示帐户创建成功确实的 Flash 消息,但是当我启动测试套件时,我收到 rspec 的错误,说它没有找到成功消息,并且确实在使用save_and_open_page 之后,屏幕上什么都没有出现......

测试日志

Started POST "/accounts" for 127.0.0.1 at 2017-05-04 18:27:20 +0200
Processing by AccountsController#create as HTML
  Parameters: {"utf8"=>"✓", "account"=>{"name"=>"Test"}, "commit"=>"Create        account"}
  [1m[36m (0.1ms)[0m  [1mSAVEPOINT active_record_1[0m
  [1m[35mSQL (0.3ms)[0m  INSERT INTO "accounts" ("name",    "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["name",    "Test"], ["created_at", "2017-05-04 16:27:20.224700"], ["updated_at",  "2017-05-04 16:27:20.224700"]]
  [1m[36m (0.1ms)[0m  [1mRELEASE SAVEPOINT active_record_1[0m
Redirected to http://localhost/
Completed 302 Found in 6ms (ActiveRecord: 0.7ms)
Started GET "/" for 127.0.0.1 at 2017-05-04 18:27:20 +0200 
Processing by PagesController#home as HTML
  Rendered pages/home.html.erb within layouts/home (5.0ms)
  Rendered shared/_navbar_home.html.erb (1.1ms)
  Rendered shared/_flashes.html.erb (0.1ms)
  Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 10ms (Views: 9.4ms | ActiveRecord: 0.0ms)

【问题讨论】:

  • 将失败测试的 test.log 输出添加到您的问题中。
  • 我用日志编辑了我的问题
  • 日志显示它正在重定向到root,因此帐户创建可能成功,您实际上是如何显示的(他们是否需要JS出现在页面上)?
  • 是的,这也是我的想法。它们不需要任何 JS,它是我在测试是否存在通知或警报后放置的纯 html。奇怪的是它在开发中完美运行..
  • 可能存在的一个问题是它重定向到localhost,因此会话cookie(包含flash)可能被设置在主机127.0.0.1(或www.example. com 等,具体取决于原始请求的发送位置),因此不会与重定向一起发送。知道初始请求使用的是什么主机名吗?

标签: ruby-on-rails ruby rspec capybara integration-testing


【解决方案1】:

最好的猜测是您最初的visit root_path 正在使用“www.example.com”的rack_test 驱动程序default_host。这意味着会话 cookie(包含 flash)正在为“example.com”设置,因此当应用程序重定向到 http://localhost 时不会发送,因为域不匹配。一种解决方案是从redirect_to :root(最终调用url_for(:root) 来确定目的地)更改为redirect_to root_path,在重定向时只使用当前主机名。

【讨论】:

  • 就是这样!我确实在寻找 default_host 参数,因为我很确定错误来自那里。现在像魅力一样工作,再次感谢。