DEV Community

r7kamura
r7kamura

Posted on

8 3

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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (1)

Collapse
 
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!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay