Alan W. Smith
Alan W. Smith

Reputation: 25425

Embed RSpec test in a Ruby class

I often build little single-purpose Ruby scripts like this:

#!/usr/bin/env ruby

class Widget

  def end_data
    DATA.read
  end

  def render_data source_data
    source_data.upcase
  end

end

w = Widget.new
puts w.render_data(w.end_data)

__END__
data set to work on.

I'd like to include RSpec tests directly inside the file while I'm working on it. Something like this (which doesn't work but illustrates what I'm trying to do):

#!/usr/bin/env ruby

class Widget

  def end_data
    DATA.read
  end

  def render_data source_data
    source_data.upcase
  end

  def self_test
    # This doesn't work but shows what I'm trying to 
    # accomplish. The goal is to have RSpec run these type  
    # of test when self_test is called.
    describe "Widget" do
      it "should render data properly" do
        @w = Widget.new
        expect(@w.render_data('test string')).to eq 'TEST STRING'
      end
    end
  end

end

w = Widget.new
w.self_test

__END__
data set to work on.

I understand this is not the normal way to work with RSpec and isn't appropriate in most cases. That said, there are times when it would be nice. So, I'd like to know, is it possible?

Upvotes: 1

Views: 242

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

There are two things. First off rspec by default won't pollute the global namespace with methods like describe and so on. The second thing is that you need to tell rspec to run the specs after they've been declared.

If you change your self_test method to be

RSpec.describe "Widget" do
  it "should render data properly" do
    @w = Widget.new
    expect(@w.render_data('test string')).to eq 'TEST STRING'
  end
end
RSpec::Core::Runner.invoke

(having of course done require 'rspec' then that will run your specs).

The invoke methods exits the process after running the specs. If you don't want to do that, or need more control over where output goes etc. you might want to drop down to the run method which allows you to control these things.

Upvotes: 2

Related Questions