1

I am using clamp - the command line framework for my ruby application, and am unsure of how to initiate my clamp objects for unit testing. My clamp object looks like this

class myCommand < Clamp::Command
  parameter "first", "first param"
  parameter "second", "second param"

  def execute
    #Data
  end
end

And is run via command line like so

$~> myCommand first second

At the moment, in my rspec tests im having to set the objects properties directly like so.

  before(:each) do
   $stdout = StringIO.new
   @my_command = myCommand.new("")
   @my_command.first= "first"
   @my_command.second= "second"
 end

This doesnt seem to be the proper way to initiate the clamp objects for testing, but am unsure of the correct way to do this. Wondered if anyone had any ideas. Thanks

1 Answer 1

2

So, what you're doing is:

  • creating a Command instance
  • setting attributes on it
  • calling #execute

That's a fine way to test a Clamp command, and is probably the best way to unit-test the logic of your #execute method.

If you wish to test parsing of command-line arguments, you could exercise the #parse method, and check attribute values, e.g.

before do
  @command = MyCommand.new("my")
end

describe "#parse" do

  before do
    @command.parse(["FOO", "BAR"])
  end

  it "sets attribute values" do
    @command.first.should == "FOO"
    @command.second.should == "BAR"
  end

end

But this starts to test Clamp itself, rather than your own code ... so I probably wouldn't bother.

If you want to test both parsing and execution together, try something like:

describe ".run" do
  context "with two arguments" do
    it "does something useful" do
      MyCommand.run("cmd", ["ARG1", "ARG2"])
      # ... test for usefulness
    end
  end
end

Again, though, the way you're currently testing is perfectly fine. I hope that helps.

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

1 Comment

Great answer, exactly what I was looking for. I am only interested in testing the code in the execute method, so was looking for a cleaner way to initialize my command object in the "before" method. I will use @command.parse to help me to do this.

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.