Saad
Saad

Reputation: 1902

How to test rake task when arguments are passed

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\]

Upvotes: 1

Views: 1104

Answers (1)

brainbag
brainbag

Reputation: 1057

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

Upvotes: 3

Related Questions