r7kamura
Posted on August 4, 2022
Let me introduce yardspec in this article.
yardspec is a Ruby gem that supports executing YARD documentation @example
s 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.
Further reading
-
https://github.com/r7kamura/yardspec
- yardspec source code
-
https://www.rubydoc.info/gems/yard/file/docs/Tags.md#example
- YARD
@example
tag
- YARD
-
https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html
- Rust doctest
Posted on August 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.