如何在运行 Rspec 功能测试之前创建登录用户



我正在尝试编写一个功能测试(使用 Rspec 3 和 Capybara(,测试用户添加地址(字符串(并获取坐标作为响应。用户需要先登录才能执行此操作,那么如何创建用户然后执行此功能?我收到以下错误:

Failure/Error: fill_in 'text_field_tag', with: q
     Capybara::ElementNotFound:
       Unable to find field "text_field_tag" that is not disabled

这是我到目前为止的代码。

find_coordinates_spec.rb

feature 'find coordinates' do
  scenario 'with valid place name' do
    user = User.create(email: 'test@test.com', password: "password", password_confirmation: "password")
    sign_in user
    geocode('London')
    expect(page).to have_content('51.5073219, -0.1276474')
  end
  def geocode(q)
    visit locations_path
    fill_in 'text_field_tag', with: q
    click_button 'geocode'
  end
end

locations_controller.rb

class LocationsController < ApplicationController
  before_action :authenticate_user!
  def index
    if params[:q].blank?
      @message = 'Please enter an address in the field!'
      return
    end
    token = Rails.application.credentials.locationiq_key
    search = LocationiqApi.new(token).find_place(params[:q])
    # Hash#dig will return nil if ANY part of the lookup fails
    latitude = search.dig('searchresults', 'place', 'lat')
    longitude = search.dig('searchresults', 'place', 'lon')
    if latitude.nil? || longitude.nil?
      # Output an error message if lat or lon is nil
      @coordinates = "We couldn't find a place by this name. Please enter a valid place name."
    else
      @coordinates = "Coordinates: " + "#{latitude}, #{longitude}"
    end
  end
end

地点.html.erb

<main>
  <h1>Location Search</h1>
  <!-- devise flash messages -->
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <!-- Button to search coordinates -->
  <%= form_tag(locations_path, method: :get) do %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("geocode") %>
    <%= @message %>
  <% end %><br>
  <%= @coordinates %>
</main>

您的错误不是因为无法创建用户。为了确保身份验证正常,您可以在visit locations_path后添加:

  expect(page).to have_content('Please enter an address in the field')

实际错误是您的输入字段被称为q而不是text_field_tag

  fill_in "q", with: q
由于

以下行,您收到此错误:

fill_in 'text_field_tag', with: q

根据水豚关于#fill_in的文件:

可以通过字段的名称、id、Capybara.test_id属性或标签文本找到该字段

text_field_tag 不是 html 属性,而是 rails 视图帮助程序。您应该更改 ID 或名称text_field_tag

最新更新