Michael Durrant
Michael Durrant

Reputation: 96574

Ruby-rspec - how to print out the test (group) name

If I have some test, e.g.

  require_relative "Line"
  require_relative "LineParser"

  describe Line do

    it "Can be created" do
      load "spec_helper.rb"
      @line.class.should == Line
    end 
    it "Can be parsed" do
    ...

How can I print out the test group name - "Line" in this case.

I tried adding:

    before :all do
      puts "In #{self.class}"
    end

but that gives: In RSpec::Core::ExampleGroup::Nested_3, not Line

Upvotes: 14

Views: 9424

Answers (4)

dancow
dancow

Reputation: 3388

You may have specific reasons for wanting access to the test name while you're in the test...however, just in case it fits your needs to just have the line output in the test report, I like this configuration:

RSpec.configure do |config|

   # Use color in STDOUT
  config.color = true

  # Use color not only in STDOUT but also in pagers and files
  config.tty = true

  # Use the specified formatter
  config.formatter = :documentation 

end

This gives me output like:

MyClassName
  The initialization process
    should accept two optional arguments

Upvotes: 20

kwerle
kwerle

Reputation: 2401

Since I'm sure I'll be back here, this is what I want:

(byebug) $stdout.puts("#{self.class.metadata[:file_path]}:#{self.class.metadata[:line_number]}")
./spec/models/my_model_spec.rb:133

Upvotes: 0

seancdavis
seancdavis

Reputation: 2821

RSpec will read command line arguments from a file, so you could add the following to a .rspec file in the root of your project:

--format documentation
--color

(This file may already exist depending on the gem you're using for RSpec and how you've installed it.)

Upvotes: 11

Michael Durrant
Michael Durrant

Reputation: 96574

The answer turned out to be:

  before :all do
    puts "In #{self.class.description}"
  end

$ rspec line_spec.rb 
In Line

Upvotes: 8

Related Questions