0
votes

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.

1
If you don't want to test part of your method then your method should be split up into two (or more) methods.Andrew Marshall
Oh, this is not a method at all. It is just a begin end statement at the end of the file which has code wrapped in. So, it is like: begin some Ruby code endSait Mesutcan Ilhaner
If you don't want something to be a unit of code, don't make it a single unit of code.Dave Newton
I see I misunderstood your explanation. In that case, wrap it in a method!Andrew Marshall
@Sait: This doesn't sound like unit tests would be appropriate here. You're basically trying to write some kind of integration test here. If it's not a unit, you can't unit-test it.Niklas B.

1 Answers

1
votes

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?