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指出这种方法.
小智 92
我用_url替换了_path方法,以实现将完整的url与参数进行比较.
current_url.should == people_url(:search => 'name')
Run Code Online (Sandbox Code Playgroud)
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)
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)
希望这可以帮助.