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

时间:2011-03-08 04:31:42

标签: ruby-on-rails ruby-on-rails-3 rspec capybara

页面网址类似/people?search=name 虽然我使用了水豚的current_path方法,但它仅返回/people

current_path.should == people_path(:search => 'name')

但它没有说

expected: "/people?search=name"
got: "/people"

我们如何通过?有办法吗?

6 个答案:

答案 0 :(得分:201)

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

使用示例:

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

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

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

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

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

感谢Tom Walpole指出这种方法。

答案 1 :(得分:90)

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

current_url.should == people_url(:search => 'name')

答案 2 :(得分:49)

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

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

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

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

如果想要匹配完整的网址

expect(page).to have_current_path(people_url, url: true) # Capybara < 2.16
expect(page).to have_current_path(people_url) # Capybara >= 2.16

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

expect(page).to have_current_path(/search=name/)

答案 3 :(得分:17)

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

要获取路径和查询字符串,例如Rails中的request.fullpath,您可以执行以下操作:

URI.parse(current_url).request_uri.should == people_path(:search => 'name')

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

def current_fullpath
  URI.parse(current_url).request_uri
end

希望这有帮助。

答案 4 :(得分:0)

编辑:正如Tinynumberes所提到的,对于具有端口号的URL,此操作失败。保留在这里以防其他人有同样的好主意。

current_url[current_host.size..-1]

高尔夫球场(35个角色)与URI.parse(current_url).request_uri一样,但可能更快,因为没有明确的URI解析。

我已经发出拉动请求,将其添加到Capybara:https://github.com/jnicklas/capybara/pull/1405

答案 5 :(得分:0)

请注意作者提到的 in this comment。 使用 current_url 会导致不稳定的测试。