在水豚中访问'route'和访问'/route'有什么区别吗?

Is there any difference between visit 'route' and visit '/route' in Capybara?

以下测试有时会失败:

it 'can create a new item' do 
  visit 'items/new' 
  within 'form#item-form' do 
    fill_in 'Name', with: 'Item'
    click_button 'Create'
  end

  current_path.must_equal('/items')
  assert page.has_content?('Item')
end

我在within块之前放了一个puts page.html,发现有时页面会是一个清晰的'Not found'页面。我正在使用 Capybara 的默认网络驱动程序 Rack::Test

访问'route'和访问Capybara的'/route'有什么区别吗?

是的,在很多情况下可能会有所不同,具体取决于您是否指定了 Capybara.app_host、是否已经在当前测试中访问了 url 等。基本上如果您想要转到 /items/new 指定 /items/new

使用rack-test可以看到相关代码here and here。其他驱动程序都有类似的行为,所以只有在您真正了解自己在做什么并且需要相对路径时才使用相对路径

另一方面,您应该避免对 current_path 进行直接断言。当您使用 rack-test 时,它会正常工作,因为所有对提交、链接等的点击都是同步的 - 但是 if/when 您转向使用支持 JS 的驱动程序,这些操作不再保证同步,因此您将结束在实际更改之前比较 current_path 。你应该习惯使用

assert page.has_current_path?('/items')

因为这将在确认当前路径时使用水豚的等待行为