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

kri*_*sna 139 rspec ruby-on-rails capybara ruby-on-rails-3

页面网址就像/people?search=name 我使用current_path的水豚方法一样/people只返回.

current_path.should == people_path(:search => 'name')
Run Code Online (Sandbox Code Playgroud)

但它没有说

expected: "/people?search=name"
got: "/people"
Run Code Online (Sandbox Code Playgroud)

我们怎么能通过?有没有办法做到这一点?

nzi*_*nab 204

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

用法示例:

expect(page).to have_current_path(people_path(search: 'name'))
Run Code Online (Sandbox Code Playgroud)

正如您在文档中看到的,可以使用其他选项.如果当前页面是,/people?search=name但您只关心它在/people页面上而不管参数如何,您可以发送only_path选项:

expect(page).to have_current_path(people_path, only_path: true)
Run Code Online (Sandbox Code Playgroud)

此外,如果您想比较整个网址:

expect(page).to have_current_path(people_url, url: true)
Run Code Online (Sandbox Code Playgroud)

感谢Tom Walpole指出这种方法.

  • 对于新的 Capybara 版本,请使用 `ignore_query: true` 而不是 `only_path: true` (6认同)
  • 我很快就会需要这种语法,我正在为遗留应用程序编写测试.使用`current_path.should ==`现在正在工作(虽然我需要添加一个尾随的正斜杠作为字符串).我提前感谢你提供我可能需要的代码. (4认同)
  • `URI.parse(current_url).request_uri`更简洁.见@Lasse Bunk的回答. (3认同)

小智 92

我用_url替换了_path方法,以实现将完整的url与参数进行比较.

current_url.should == people_url(:search => 'name')
Run Code Online (Sandbox Code Playgroud)

  • 您也可以在较新版本的Capybara中使用`current_path`并将其与`people_path(...)匹配 (11认同)
  • 你是如何处理主持人部分的? (4认同)

Tho*_*ole 50

只是为了现代更新这个问题.使用Capybara 2.5+时检查current_paths的当前最佳实践是使用current_path匹配器,它将使用Capybaras等待行为来检查路径.如果想要检查request_uri(路径和查询字符串)

expect(page).to have_current_path(people_path(:search => 'name'))  
Run Code Online (Sandbox Code Playgroud)

如果只想要路径部分(忽略查询字符串)

expect(page).to have_current_path(people_path, only_path: true) # Capybara < 2.16
expect(page).to have_current_path(people_path, ignore_query: true) # Capybara >= 2.16
Run Code Online (Sandbox Code Playgroud)

如果想要匹配完整的URL

expect(page).to have_current_path(people_url, url: true) # Capybara < 2.16
expect(page).to have_current_path(people_url) # Capybara >= 2.16
Run Code Online (Sandbox Code Playgroud)

匹配器将采用与==或正则表达式进行比较的字符串来匹配

expect(page).to have_current_path(/search=name/)
Run Code Online (Sandbox Code Playgroud)

  • 在这些现代时期,这应该标记为*答案.这将安全很多模糊的时间问题,谢谢! (4认同)

Las*_*unk 17

我知道已经选择了答案,但我只是想提供一个替代解决方案.所以:

要获得路径和查询字符串,就像request.fullpath在Rails中一样,您可以:

URI.parse(current_url).request_uri.should == people_path(:search => 'name')
Run Code Online (Sandbox Code Playgroud)

你也可以像你一样在你的测试类中做一个帮助方法(就像ActionDispatch::IntegrationTest我做的那样):

def current_fullpath
  URI.parse(current_url).request_uri
end
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.