Run YARD as RSpec

r7kamura

r7kamura

Posted on August 4, 2022

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(Foo::Bar.new.baz).to eq('baz')
    #
    # @example returns "bazbaz" for count 2
    #   expect(Foo::Bar.new.baz(count: 2)).to eq('bazbaz')
    #
    # @return [String]
    def baz(count: 1)
      'baz' * count
    end
  end
end
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(Foo::Bar.new.baz).to eq('baz')
  end

  it 'returns "bazbaz" for count 2' do
    expect(Foo::Bar.new.baz(count: 2)).to eq('bazbaz')
  end
end
Enter fullscreen mode Exit fullscreen mode

and running RSpec as follows will automatically test them.

$ bundle exec rspec

Foo::Bar#baz
  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

💖 💪 🙅 🚩
r7kamura
r7kamura

Posted on August 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Run YARD as RSpec
ruby Run YARD as RSpec

August 4, 2022