使用Capybara + RSpec测试页面重定向

Ale*_*nes 10 rspec capybara

我有一个step_definition

Then(/^I should be redirected to the (.+?) page/) do |target|
  expect(current_url).to eq(Urls[target])
end
Run Code Online (Sandbox Code Playgroud)

一般来说效果很好.有时当我使用恶作剧驱动程序时,它比平时更快,而current_url仍然是旧页面.那是我得到这样的错误:

Then I should be redirected to the login page                                                # features/step_definitions/navigate-steps.rb:64

expected: "http://example.com/"
got: "http://example.com/reset-password"

(compared using ==)
(RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/navigation.rb:50:in `/^I should be redirected to the (.+?) page$/'
features/password.feature:100:in `Then I should be redirected to the login page'
Run Code Online (Sandbox Code Playgroud)

有没有办法让匹配器等待一点url更新?

Tho*_*ole 22

不要将eq匹配器用于current_pathcurrent_url.相反,请使用have_current_pathCapybara 2.5+提供的匹配器

expect(page).to have_current_path(Urls[target], url: true)
Run Code Online (Sandbox Code Playgroud)

have_current_path匹配使用水豚的等待/重试的行为,所以它会等待页面更改.我添加了url: true选项,使其比较完整的URL.如果Urls[target]仅解析为路径,则可以删除该选项.