[rspec-users] Custom Formatter: Getting Text from It Method

David Chelimsky dchelimsky at gmail.com
Fri Sep 30 16:35:17 EDT 2011

On Sep 28, 2011, at 7:30 AM, Jeff Nyman wrote:

> Hey all.
> I've been playing around with RSpec custom formatters to see how much
> flexibility there is. One thing I've been trying to see is if I can
> print the contents of a variable that's in an example (it) method. So,
> for example, here's what I have in my specification:
>  it "should display results range" do
>    search_for("star wars")
>    @browser.text.should match(/Showing .* of .* Results/)
>    intent = "Text 'Showing .* of .* Results' shows after 'Star Wars'
> search"
>  end
> Notice the line with intent there? I realize this is not what most
> people would do with RSpec. The reason I'm doing this is because I'd
> like viewers of the test results to see the exact condition that was
> tested for in the should if they want to -- without having to read the
> code. Again, I'm just experimenting.
> What I'm trying to do is figure out how I could use a custom formatter
> to print out that intent text. I know that the example_passed method
> in the formatters contains elements like example.description that
> prints out the text of the it method. But trying @output.puts
> example.intent does not seem to work.
> Is there a better way to do what I'm trying to do here? Again, I
> realize that most people are happy with the describe and it text being
> printed out. But sometimes people -- like my business users -- want to
> check the actual condition that was checked for, without having to
> read Ruby code.
> Any pointers or tips would be greatly appreciated.
> - Jeff

The variables defined inside the example are out of scope in the formatter. You can do something like this:

require 'rspec/core/formatters/base_text_formatter'

module ExtraDoc
  def example_passed(example)
    example.description << ": #{example.metadata[:extra_doc]}"

RSpec::Core::Formatters::BaseTextFormatter.send(:include, ExtraDoc)

describe "something" do
  it "does something", :extra_doc => "with extra sauce" do

Output from `rspec --format documentation` is:

  does something: with extra sauce

That said, I'd focus on naming the examples better so they serve the needs of all readers.


More information about the rspec-users mailing list