Skip to content

Instantly share code, notes, and snippets.

@Qqwy
Created March 9, 2022 23:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qqwy/555d7ea83bdf633fbd109811c1a1b40f to your computer and use it in GitHub Desktop.
Save Qqwy/555d7ea83bdf633fbd109811c1a1b40f to your computer and use it in GitHub Desktop.
Example of how to integrate doctests with Ruby Minitest
# Example of how to integrate doctests with Ruby Minitest
#
# Besides depending on `minitest`,
# this functionality depends on the `doctest-core` gem, c.f. https://www.rubydoc.info/gems/doctest-core/
class YourAppName::TestCase < MiniTest::Test
# To be used inside the body of a tests-class
# It will automatically create test cases for all
# 'documentation test' snippets that exist in the comments
# above the methods in `klass`.
#
def self.doctest!(klass)
doctests = Doctest::Core.extract_from(klass)
return puts "Note: Attempting to extract doctests for #{klass}, but none were found (at: #{caller_locations.first})" if doctests.empty?
doctests.each do |doctest|
file_location = Pathname.new(doctest.original_file).relative_path_from(Rails.root)
define_method("test_ (doctest) #{file_location}:#{doctest.line}") do
message = "While running doctest: \n\t#{doctest.code_string}\n"
assert_equal(doctest.result_evaluation, doctest.code_evaluation, message)
end
end
end
end
@Qqwy
Copy link
Author

Qqwy commented Mar 9, 2022

You can then use it as

# for instance, in app/models/user.rb
class User
  attr_accessor :first_name, :last_name

  # Shows the user's printable name
  # 
  # >> bob = User.new()
  # >> bob.first_name = "Bob"
  # >> bob.last_name = "Ross"
  # >> bob.full_name
  # => "Bob Ross"
  def full_name
    "#{self.first_name} #{self.last_name}"
  end
end
# for instance, in test/unit/models/user_test.rb
require 'test_helper'

class UserTest < YourAppName::TestCase
  doctest!(User)
end

And then when running minitest, this example will run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment