Sait Mesutcan Ilhaner
Sait Mesutcan Ilhaner

Reputation: 367

Testing execution code with RSpec

I have piece of code to test that is not wrapped in a method. It just stands alone with itself in a Ruby class.

begin
  # Do stuff - bunch of Ruby code
end

This is not a Rails app. It's a standalone Ruby class. I don't want to execute the whole begin end statement in my rspec tests. How do you test something like this? Should it be done using mocks/stubs? I asked a couple of people but they also didn't know the answer.

Upvotes: 0

Views: 206

Answers (1)

Eric Saxby
Eric Saxby

Reputation: 46

I've found that this is easier to test if you can encapsulate the behavior in a method or a module, but it really depends on what code you're trying to execute. If the code winds up altering the class in a public fashion, you can write tests around the fact that the class behaves as expected in memory. For instance:

class Foo
  attr_accessor :bar
end

describe Foo
  it "should have an attr_accessor bar" do
    foo = Foo.new
    foo.bar = "baz"
    foo.bar.should == "baz"
  end
end

This becomes more difficult if you're altering the class in a way that is private.

I've had luck in the past by rewriting this type of behavior into a method that can be explicitly called. It makes testing a lot easier, as well as make it a lot easier to understand timing when troubleshooting problems. For instance:

class Foo
  def self.run
    # do stuff
  end
end

Can you provide a little more context of what you're trying to do in your class?

Upvotes: 1

Related Questions