Brand
Brand

Reputation: 1701

sandbox testing environments exist for TDD'ing command line application

I'm writing a command line command but want to TDD it. I'll be creating and deleting files and was wondering if there's a sandbox testing gem or something like that. I'm using ruby and rspec.

Upvotes: 0

Views: 339

Answers (3)

avh4
avh4

Reputation: 2655

You might also want to take a look at the sandbox gem.

gem install sandbox

Example usage is here: https://github.com/bdimcheff/sandbox

Upvotes: 0

avh4
avh4

Reputation: 2655

The template generated by the newgem install_cucumber generator uses a pattern that I like quite a bit. Have a look at the support/env.rb and support/common.rb files it creates:

Use of it in test looks like this:

in_tmp_folder do
  # The current directory is now a generated tmp folder.
  # If you stick to relative paths, everything you do in here should be safe
end

The files linked to above are for using this in cucumber tests, but it could easily be adapter to whatever framework you're using. The env.rb above deletes the tmp folder before each test starts.

Upvotes: 0

bcarlso
bcarlso

Reputation: 2345

Depends on what you're trying to do, but I test most of my command line Ruby by mocking out the file system and STDIN/STDOUT. Using dependency injection I often end up with something along these lines:

describe Add do
  it 'writes the result to standard out' do
    console = mock('STDOUT')
    console.should_receive(:puts).with('5')

    Add.new(console).execute(3,2)
  end
end

class Add
  def initialize(out = STDOUT)
    @out = out
  end

  def execute(command_line_args)
    @out.puts(command_line_args.inject(:+))
  end
end

Add.new.execute(ARGS)

By using default values I can inject in the test, but leave it out of the production code.

Hope that helps!

Brandon

Upvotes: 2

Related Questions