DEV Community


Posted on

Run YARD as RSpec

Let me introduce yardspec in this article.

yardspec is a Ruby gem that supports executing YARD documentation @examples as RSpec examples.

module Foo
  class Bar
    # @example returns "baz"
    #   expect( eq('baz')
    # @example returns "bazbaz" for count 2
    #   expect( 2)).to eq('bazbaz')
    # @return [String]
    def baz(count: 1)
      'baz' * count
Enter fullscreen mode Exit fullscreen mode

It interprets the documentation examples above as the following RSpec examples:

RSpec.describe 'Foo::Bar#baz' do
  it 'returns "baz"' do
    expect( eq('baz')

  it 'returns "bazbaz" for count 2' do
    expect( 2)).to eq('bazbaz')
Enter fullscreen mode Exit fullscreen mode

and running RSpec as follows will automatically test them.

$ bundle exec rspec

  returns "baz"
  returns "bazbaz" for count 2

Finished in 0.00129 seconds (files took 0.087 seconds to load)
2 examples, 0 failures
Enter fullscreen mode Exit fullscreen mode

As you may have noticed, this is the doctest concept from Rust, Python, Elixir, etc, dropped into RSpec and YARD for Ruby.

It is often helpful to include example code in your documentation and demonstrate the results of executing them. But it is important to ensure that the documentation stays up-to-date with the code.

That is the purpose for which yardspec was created. By writing example code that actually works, users can read it with confidence and try it out for themselves.

Further reading

Top comments (1)

katafrakt profile image
Paweł Świątkowski

Oh, cool. I knew it was possible in other languages, but did not know it's possible in Ruby. Thanks for the post!