I've looked through a few posts with the same issue, but still feel like mine is a bit different.
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
when I run rspec
, I'm getting an error:
Failures:
1) Users can view categories with the category details Failure/Error: 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>'
Then I've modified spec by adding 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
This time I got error:
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>'
I noticed that sometimes, I'm not seeing the error and sometimes it shown up.
The only thing I see always is "http://www.example.com/categories/17"
.
This part remains same always when I run rspec
command.
The full source code is here https://github.com/tenzan/kaganat
答案 0 :(得分:2)
“ http://www.example.com/categories/17”网址是恒定不变的,并且当您的测试似乎只能创建一个测试时,水豚在页面上看到两个“房地产”链接,这使我相信您还有一些旧数据在您的测试数据库中。通过选择使用match: :first
,您已经掩盖了以下事实:现有记录比预期的多,并且错误应该是您的第一个线索(以及仅查看测试运行的屏幕截图)。像
rails db:reset RAILS_ENV=test
将清除您的测试数据库,并确保您没有旧数据徘徊。您还希望返回没有:match设置的原始click_link('Real Estate')
。此外,如果要进行稳定的测试,则几乎不应该对Capybara返回的对象使用标准的RSpec匹配器(“ eq”等),因为页面加载/行为是异步的。相反,您应该使用水豚提供的匹配器。在您当前的示例中,这意味着您应该写expect(page.current_url).to eq category_url(category)
expect(page).to have_current_path(category_url(category))