Skip to content

Ruby Testing

Ruby tests for vanilla Ruby or Ruby on Rails should use the rspec BDD test library.

There is currently a requirement for the workspace to contain a spec folder at the root level.

There also needs to be a Gemfile at the root level with the following contents: gem 'rspec', '3.1'.

NB: There is older Ruby content that uses the Codex SCT test type and a custom test runner. This should be avoided for future Ruby content.

Ruby test structure

  • Ruby tests are written in rspec format with describe and it blocks. If the test file finishes execution without raising an uncaught Error, the test passes.

Example Tests

# Use these lines to enable access to learner variables:
$b = binding
eval('./script.rb'), $b)

describe "script.rb" do
  it "test case name..." do
    # Test variable existence:
      # Attempt to access a learner variable
    rescue NameError
      # If variable doesn't exist, deliberately raise a new error.
      expect(1).to eq(0), "Define a variable named `my_string`."

    # If no error is raised above, variable exists and can be 
    expect($b.eval('my_string')).to be_a(String), '`my_string` should be a String.'

This test intends to evaluate whether a learner has created a new variable (my_string) and that is the correct type. The begin-rescue-end pattern is a friendly way to provide specific feedback whether the learner

  • has run tests without writing any code or with a misnamed variable ("Define a variable named my_string.")
  • has successfully created a variable but not of the right type ("my_string should be a String.")

If there are multiple variables to be tested in a single test, you can verify them in a single begin-rescue-end group with the following pattern:

rescue NameError => e
  # extract the variable name from the NameError message:
  message = e.message.match(/variable or method `([a-z_][a-zA-Z_0-9]*)/)
  # The missing variable will be interpolated in the message to learners:
  expect(1).to eq(0), "Define a variable called `#{message[1]}`."

Other Guidelines

  • Actual code (real variable names, language syntax, etc. ) in feedback messages should be code-ticked (`)
  • Ruby tests should follow Test standards.

Do you have feedback on this testing documentation? Please let us know and fill out the Feedback Form. Thank you!