使用RSpec和Capybara进行应用程序测试。我收到错误Capybara :: ElementNotFound

问题描述 投票:0回答:1

_ customers_table.html.erb

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone number</th>
      <th>Description</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @customers.each do |customer| %>
      <tr>
        <td><%= customer.name %></td>
        <td><%= customer.phone_number %></td>
        <td><%= customer.description %></td>
        <td><%= link_to customer.status.humanize, toggle_status_customer_path(customer), class: "move-to-black" %></td>
        <td><%= link_to 'Show', customer %></td>
        <td><%= link_to 'Edit', edit_customer_path(customer) %></td>
        <td><%= link_to 'Destroy', customer, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

creating_customer_spec.rb

require 'rails_helper'

describe "creating new customer", type: :feature do
  let(:customer) { customer = FactoryBot.create(:customer) }

  it 'should create new customer' do
    visit '/customers/new'
    fill_in 'Name', with: customer.name
    fill_in 'Phone number', with: customer.phone_number
    click_button 'Create Customer'
    expect(page).to have_content "#{customer.name}"
  end

  it 'should change customer status' do
    visit '/'
    click_on customer.status.humanize
    expect(customer).to have_status "move_to_white_list"
  end
end

第一个示例“应创建新客户”通行证,但第二个示例“应更改客户状态”时出错,]

Capybara::ElementNotFound:
       Unable to find link or button "Move to black list"

该元素存在,您可以在图像上看到它。如果有人可以提供帮助,我将非常感谢。enter image description here

我更改了第二个示例,现在可以了。这是我没有犯的错误好好解释一下,“黑名单”表在不同的视图上,当状态改变时,它会移到另一页,所以实际上不是可能在那找到它。

    require 'rails_helper'

describe "creating new customer", type: :feature do
  let!(:customer) { customer = FactoryBot.create(:customer) }

  it 'should create new customer' do
    visit '/customers/new'
    fill_in 'Name', with: customer.name
    fill_in 'Phone number', with: customer.phone_number
    click_button 'Create Customer'
    expect(page).to have_content "#{customer.name}"
  end

  it 'should change customer status' do
    visit '/customers'
    click_on customer.status.humanize
    expect(page).to have_content "Customer #{customer.name} moved to black list"

    visit '/black_list'
    expect(customer.reload.status).to eq "move_to_white_list"
  end
end

_ customers_table.html.erb

[[[Name ]]]]
电话号码 描述
< [
您在这里遇到许多问题。首先,您要在创建客户实例之前进入页面,这意味着它不会显示在页面上。这是因为let懒惰地求值-参见https://relishapp.com/rspec/rspec-core/v/3-8/docs/helper-methods/let-and-let-并且只会在第一次在测试中调用客户时创建客户。
visit '/' # <= no customer instance exists here click_on customer.status.humanize # <= customer instance actually created here

您可以使用始终创建客户实例的非延迟评估版本let!或在调用customer之前调用visit来解决此问题>

第二,您的测试正在修改数据库中的客户实例,但是从不重新加载您在内存中的实例(因此永远不会看到新状态)
ruby-on-rails ruby testing capybara
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.