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
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
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
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.
- yardspec source code
- Rust doctest