In my efforts to test the right stuff, I wanted to test that my basic search was working properly. I have a collection of plates that we’re storing a bunch of information on. Each plate has a unique serial number. We also have a unique id for each plate, but for our users, the serial number is what they’ll use to identify it. So I wanted to make a form that would let people search for a particular plate based on the serial number. And since this search form will be on my home controller and not the plate controller, I need to use an integration test to do this.

I’m using ransack for search. In this case, my form has one field, so this is it:

<%= search_form_for @q, :url => search_plates_path, :html => {:method => :post} do |f| %>
<%= f.submit 'Go to Incom Serial Number' %> 
	<%= f.text_field :incom_serial_number_eq %> 
<% end %>

It works perfectly. Now I want to have a test for it.

yo:mcp maryh$ rails g integration_test basic_search
      invoke  test_unit
      create    test/integration/basic_search_test.rb

I have two fixtures and I’ll search and see if I can find one of them.

  incom_serial_number: 13600-001
  incom_part_code: S203-P20-L60-O60-B08-C00
  incom_part_number: 300-2672-C

  incom_serial_number: 13600-002
  incom_part_code: S203-P20-L60-O60-B08-C00
  incom_part_number: 300-3657-A

Here’s what my integration test looks like.

require 'test_helper'

class BasicSearchTest < ActionDispatch::IntegrationTest
  fixtures :all  # Always use all, might need things in other fixtures

  def logger
  test 'find good plate' do
    get "/home/index"
    assert_response :success
    post "/plates/search", "q" =>  { "incom_serial_number_eq" =>  "13600-002"}
    assert_response :success
    assert_template "show"
    # No easy way to check the table values for the result of the search
    # Using tag ids to enable selection, get the entry, turn it into a string,
    # split it on the line break and check that the value is correct
    serial_number = css_select("td#serial_number")
    value = serial_number[0].to_s.split("
") assert_equal '13600-002</td>', value[1],"Serial Number wrong" part_code = css_select("td#part_code") value = part_code[0].to_s.split("
") assert_equal 'S203-P20-L60-O60-B08-C00</td>', value[1], "Part Code wrong" part_number = css_select("td#part_number") value = part_number[0].to_s.split("
") assert_equal '300-3657-A</td>', value[1], "Part Number wrong" end test 'do not find missing plate' do post "/plates/search", "q" => { "incom_serial_number_eq" => "1111-11"} assert_redirected_to search_path, "Not redirected correctly" assert_equal '1111-11 does not exist', flash[:notice], "Wrong flash notice" end end

I made it easy on myself by using an id in the html tags for the stuff I wanted. Then I just converted the results to a string and got it down to something I could compare. It’s probably not the prettiest test ever written, but it works, so I’m happy.