2

say we have a ruby file.rb like:

if __FILE__ == $0 then
  if ARGV[0] == 'foo'
    puts "working"
    # Dir.chdir(../)
    v = Someclass.new
    v.do_something
  end
end

it suppose to print working only if the file was triggered like ruby file.rb foo.
My question: how can that kind of stuf be tested within rspec?

My try is below. The file ran but not in the scope of rspec test:
Dir expected :chdir with (any args) once, but received it 0 times

it 'should work' do
  FILE = File.expand_path('file.rb')
  RUBY = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
  @v = Someclass.new
  Someclass.should_receive(:new).and_return @v
  @v.should_receive(:do_something)

  `#{RUBY} #{FILE} foo`
end

1 Answer 1

1

Backticks runs new shell, executes command, and returns result as a string. Thats why it runs outside your scope. Backticks does not care about contents of your script: ruby, bash, or something else.

chdir, of course, applied only to this new shell, so there seems no way to check you sample script for directory changing (except of tracing system calls). Maybe some 'real' script will do something, output more, thus providing more possibilities to check it.

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

3 Comments

Sorry for confusing, chdir was used just as an example. Edited my question. So, is it possible to test?
It depends of what do_something method does. Backticks are blackbox, which can do anything, but outputs only string. If you have complex script, and want to test it 'ruby way', maybe it is better to extract some code into library, and test that library.
It is hard to answer. You can google ruby extract some code into library. This is from first page: ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html. You can extract code into module and include module in script.

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.