【问题标题】:"Ambiguous match, found 2 elements matching visible link" issue“模棱两可的匹配,找到 2 个匹配可见链接的元素”问题
【发布时间】:2019-01-07 13:06:34
【问题描述】:

我浏览了几篇有相同问题的帖子,但仍然觉得我的有点不同。

viewing_categories_spec.rb

require 'rails_helper'

RSpec.feature 'Users can view categories' do
    scenario 'with the category details' do
        category = FactoryBot.create(:category, name: 'Real Estate')

        visit '/categories'
        click_link('Real Estate')
        expect(page.current_url).to eq category_url(category)
    end
end

category_factory.rb

FactoryBot.define do
    factory :category do
      name {"Computers"}
    end
end

当我运行 rspec 时,出现错误:

失败:

1) 用户可以通过类别详细信息查看类别 失败/错误:click_link('Real Estate')

 Capybara::Ambiguous:
   Ambiguous match, found 2 elements matching visible link "Real Estate"
 # ./spec/features/viewing_categories_spec.rb:8:in `block (2 levels) in <main>'

然后我通过添加match: :first 来修改规范:

require 'rails_helper'

RSpec.feature 'Users can view categories' do
    scenario 'with the category details' do
        category = FactoryBot.create(:category, name: 'Real Estate')

        visit '/categories'
        click_link('Real Estate', match: :first)
        expect(page.current_url).to eq category_url(category)
    end
end

这次我出错了:

Failures:

  1) Users can view categories with the category details
     Failure/Error: expect(page.current_url).to eq category_url(category)

       expected: "http://www.example.com/categories/265"
            got: "http://www.example.com/categories/17"

       (compared using ==)
     # ./spec/features/viewing_categories_spec.rb:9:in `block (2 levels) in <main>'

我注意到,有时我看不到错误,但有时会出现。

我唯一看到的总是"http://www.example.com/categories/17"。 当我运行rspec 命令时,这部分始终保持不变。

完整的源代码在这里https://github.com/tenzan/kaganat

【问题讨论】:

    标签: capybara factory-bot rspec-rails ruby-on-rails-5.2


    【解决方案1】:

    http://www.example.com/categories/17”网址是不变的,而且当您的测试似乎只创建一个时,Capybara 会在页面上看到两个“房地产”链接,这让我相信您在您的测试数据库。通过选择使用match: :first,您只是掩盖了一个事实,即存在的记录比您预期的要多,并且该错误应该是您的第一条线索(以及仅查看测试运行的屏幕截图)。类似的东西

    rails db:reset RAILS_ENV=test
    

    将清除您的测试数据库并确保您没有旧数据。您还想回到原来的 click_link('Real Estate') 而不使用 :match 设置。此外,如果你想要稳定的测试,你几乎不应该使用标准的 RSpec 匹配器('eq'等)和 Capybara 返回的对象,因为页面加载/行为是异步的。相反,您应该使用 Capybara 提供的匹配器。在您当前的示例中,这意味着您应该写 expect(page).to have_current_path(category_url(category)) 而不是写 expect(page.current_url).to eq category_url(category)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-04
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      相关资源
      最近更新 更多