1

I am testing rake task when arguments are passed, I am trying to run a rake task like this

rake do_something_after_n_number_of_days 30

when I run

let(:task) { Rake::Task['do_something_after_n_number_of_days'] }

task.invoke(30)

I get ARGV[1] as nil but when I run the rake task in the shell it works fine.

I have looked in to these answers 1 2 but all of them describe this approach

rake do_something_after_n_number_of_days[30] and I can test that with test.invoke(30) but in some shells I have to escape the brackets like this rake do_something_after_n_number_of_days\[30\]

Saad
  • 1,856
  • 1
  • 22
  • 28
  • 2
    Heed [this advice](https://stackoverflow.com/a/33087154/125816) and don't do complicated things in your rake tasks. Extract all the logic into a service object (or something) and test _that_. This way, your rake task will simply relay its ARGV to the service object, which is so simple it doesn't need to be tested. – Sergio Tulentsev Nov 20 '17 at 11:25
  • To add to my comment above, in rails it's just not worth the effort to test some types of things. Like rake tasks, controllers and views. – Sergio Tulentsev Nov 20 '17 at 12:13
  • Whether it's in a service object or not isn't relevant to the problem, they still have to be able to pass in arguments to the task. – brainbag Nov 20 '17 at 13:15
  • @brainbag: he _is_ able to pass the arguments, just not in a test. – Sergio Tulentsev Nov 20 '17 at 13:17

1 Answers1

3

It's common practice in commands to use environment variables for configuration. You'll see this used in many different gems. For your needs, you could do something like this instead:

task :do_something_after_n_number_of_days do
  raise ArgumentError, 'Invalid DAYS environment setting' if ENV['DAYS'].nil?
  puts ENV['DAYS']
end

Then you can set the ENV in your test, like this:

let(:task) { Rake::Task['do_something_after_n_number_of_days'] }

context "when DAYS is set" do 
  before { ENV['DAYS'] = '100' }

  it "does something" do 
    expect { task.invoke }.to output("100").to_stdout
  end
end

context "when DAYS is nil" do 
  before { ENV['DAYS'] = nil }

  it "raises an ArgumentError" do 
    expect { task.invoke }.to raise_error(ArgumentError, /Invalid DAYS/)
  end
end
brainbag
  • 1,007
  • 9
  • 23