且构网

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

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

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

我已经更新了此答案,以反映水豚的现代习俗。我认为这是理想的选择,因为这是公认的答案,而且在寻找解决方案时会提及许多人。话虽如此,检查当前路径的正确方法是使用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.