Skip to content

4. Using Ruby to automate repetitive tests

Elsa Perelli edited this page Oct 23, 2024 · 8 revisions

Goal

To this point, tests have followed as straightforward request-response-validate pattern. And since we have only attempted to test one resource so far, writing out the test is quick and easy. However, oftentimes when testing a system, one of the following may occur:

  1. Many tests need to be written that are extremely repetitive. Writing them out is time consuming and error prone.
  2. Creating smarter tests that can change behavior based on responses from the server enables more thorough tests, or substantially simplifies the user experience.

In the case of the HL7 FHIR US Core IG, for example, many resource types need to support search by patient. You could write them all out by hand, replacing the name of the resource as needed, but that is error prone. Instead, you can leverage Ruby to do the work for you.

In this test, we'll create a loop that performs the same "search by patient" test, except against a different resource type that needs to be supported.

Resources

Solution

Update the search tests to the following to take advantage of the pattern of requiring search by patient_id. Note the special case for Observation, DiagnosticReport, and Device Resource types.

    group do
      id :search_tests
      title 'Search Tests'

      input :patient_id

      ['AllergyIntolerance',
      'CarePlan',
      'CareTeam',
      'Condition',
      'Device',
      'DiagnosticReport',
      'DocumentReference',
      'Encounter',
      'Goal',
      'Immunization',
      'MedicationRequest',
      'Observation',
      'Procedure'].each do |resource|

        test do
          title "#{resource} Search by Patient"

          run do
            fhir_search(resource, params: { patient: patient_id })

            assert_response_status(200)
            assert_resource_type('Bundle')

            # There are not profiles for Observation, DocumentReference, or Device
            # in US Core v3.1.1
            pass_if ['Observation', 'DiagnosticReport', 'Device'].include?(resource),
              "Note: no US Core Profile for #{resource} resource type"

            assert_valid_bundle_entries(
              resource_types: {
                "#{resource}": "http://hl7.org/fhir/us/core/StructureDefinition/us-core-#{resource.downcase}"
              }
            )
          end
        end
      end
    end

link to the diff between step-4 and step-4-solution branches: https://github.com/inferno-training/inferno-tutorial/compare/step-4...step-4-solution

Note: When running this branch with the Inferno Reference Server and Patient 85, Test 2.02 will fail. This is an expected failure since Patient 85 in the reference server no longer conforms to USCore 3.1.1.