0

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.

5
  • 1
    If you don't want to test part of your method then your method should be split up into two (or more) methods. Commented Mar 21, 2012 at 23:16
  • 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 end Commented Mar 21, 2012 at 23:23
  • If you don't want something to be a unit of code, don't make it a single unit of code. Commented Mar 21, 2012 at 23:26
  • I see I misunderstood your explanation. In that case, wrap it in a method! Commented Mar 21, 2012 at 23:27
  • @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. Commented Mar 21, 2012 at 23:43

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I am trying to do bunch of file operations between begin and end statements . So, I am checking for if a file exists, if yes, execute some piece of code if it doesn't exist execute another piece of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.