I'm trying to write a feature test (using Rspec 3 and Capybara) that tests a user adding an address (string) and getting the coordinates in response. Users need to be signed in before they can do this, so how can I create a user and then perform this function? I get the following error:

Failure/Error: fill_in 'text_field_tag', with: q

     Capybara::ElementNotFound:
       Unable to find field "text_field_tag" that is not disabled

Here is the code I have so far.

find_coordinates_spec.rb

feature 'find coordinates' do
  scenario 'with valid place name' do
    user = User.create(email: '[email protected]', 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

locations.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>

2 Answers

1
Vasfed On Best Solutions

Your error is not because of failure to create a user. Just to be sure that authentication went ok you can add after visit locations_path:

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

Actual error is that your input field is called q and not text_field_tag:

  fill_in "q", with: q
0
Vincent Rolea On

Your are getting this error because of this line:

fill_in 'text_field_tag', with: q

According to Capybara documentation on #fill_in:

The field can be found via its name, id, Capybara.test_id attribute, or label text

text_field_tag is not an html attribute but a rails view helper. You should change if with the id, label or name of the text_field_tag