且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Capybara 获取带有查询字符串的当前路径

更新时间:2023-02-23 08:31:41

我已更新此答案以反映水豚的现代惯例.我认为这是理想的,因为这是公认的答案,也是许多人在寻找解决方案时所参考的答案.话虽如此,检查当前路径的正确方法是使用 Capybara 提供的 has_current_path? 匹配器,如下所述:点击这里

I've updated this answer to reflect modern conventions in capybara. I think this is ideal since this is the accepted answer, and what many people are being referred to when looking for a solution. With that said, the correct way to check the current path is to use the has_current_path? matcher provided by Capybara, as documented here: Click Here

示例用法:

expect(page).to have_current_path(people_path(search: 'name'))

正如您在文档中所见,还有其他选项可用.如果当前页面是 /people?search=name 但你只关心它在 /people 页面上而不考虑参数,你可以发送 only_path 选项:

As you can see in the documentation, other options are available. If the current page is /people?search=name but you only care that it's on the /people page regardless of the param, you can send the only_path option:

expect(page).to have_current_path(people_path, only_path: true)

另外,如果你想比较整个 URL:

Additionally, if you want to compare the entire URL:

expect(page).to have_current_path(people_url, url: true)

感谢 Tom Walpole 指出这种方法.

Credit to Tom Walpole for pointing out this method.