首页 > 解决方案 > 如何在 rspec 中使用 capybara 点击导航栏中的链接?

问题描述

我有这个代码

require 'rails_helper'

RSpec.describe 'planets features' do
  describe 'adding a new planet' do
    it 'adds a planet to the list of planets' do
      visit planets_path
      click_link('List your planet')

      expect(current_path).to have_content('/planets/new')

      fill_in('Name', with: 'Test')
      click_button('Publish')

      expect(current_path).to have_content('/planets')
      expect(page).to have_content('Test')

    end
  end
end

它在终端中显示此错误:

行星功能添加新行星将行星添加到行星列表失败/错误:click_link('列出你的星球')

 Capybara::ElementNotFound:
   Unable to find link "List your planet"
The link I want to click is in the navbar.
Here is a part of the code in the navbar with the link 'List your planet'.

<div class="navbar navbar-expand-sm navbar-light navbar-lewagon">
  <%= link_to planets_path, class: "navbar-brand" do %>
    <p class="navbar-logo"><i class="fas fa-meteor"></i> PIANETA</p>
    <% end %>

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>


  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <% if user_signed_in? %>

        <%= link_to "List your planet", new_planet_path, class: "btn btn-outline-primary-1 shadow-none focus-none text-decoration-none", type: "button", role: "button" %>
        <%= link_to "My Listings", planets_path, class: "btn btn-outline-primary-1 shadow-none focus-none text-decoration-none", type: "button", role: "button" %>

如何正确编写测试,以便在导航栏中找到链接?

标签: rspeccapybaranavbar

解决方案


对我来说,它看起来不像一个链接,而是一个按钮(基于类名和类型)。

试试click_button('List your planet')

如果这不起作用,请尝试find('.btn', :text => 'List your planet').click


推荐阅读