Testing a method defined in a rake task
Asked Answered
C

3

11

I want to test a method defined in a rake task.

rake file

#lib/tasks/simple_task.rake
namespace :xyz do
    task :simple_task => :environment do
        begin
            if task_needs_to_run?
                puts "Lets run this..."
                #some code which I don't wish to test
                ...
            end
        end
    end
    def task_needs_to_run?
        # code that needs testing
        return 2 > 1
    end

end

Now, I want to test this method, task_needs_to_run? in a test file How do I do this ?

Additional note: I would ideally want test another private method in the rake task as well... But I can worry about that later.

Chadd answered 20/1, 2012 at 10:58 Comment(1)
You can use defined?( task_needs_to_run? ) # => true.Ginaginder
F
8

You can just do this:

require 'rake'
load 'simple_task.rake'
task_needs_to_run?
=> true

I tried this myself... defining a method inside a Rake namespace is the same as defining it at the top level.

loading a Rakefile doesn't run any of the tasks... it just defines them. So there is no harm in loading your Rakefile inside a test script, so you can test associated methods.

Further answered 26/1, 2012 at 21:19 Comment(2)
Can you please elaborate on this? I'm sorry I could not followChadd
@Shikher, I did some experimentation and came up with a much better answer. Have a look!Further
O
9

The usual way to do this is to move all actual code into a module and leave the task implementation to be only:

require 'that_new_module'

namespace :xyz do
  task :simple_task => :environment do
    ThatNewModule.doit!
  end
end

If you use environmental variables or command argument, just pass them in:

ThatNewModule.doit!(ENV['SOMETHING'], ARGV[1])

This way you can test and refactor the implementation without touching the rake task at all.

Oxonian answered 20/1, 2012 at 12:30 Comment(0)
F
8

You can just do this:

require 'rake'
load 'simple_task.rake'
task_needs_to_run?
=> true

I tried this myself... defining a method inside a Rake namespace is the same as defining it at the top level.

loading a Rakefile doesn't run any of the tasks... it just defines them. So there is no harm in loading your Rakefile inside a test script, so you can test associated methods.

Further answered 26/1, 2012 at 21:19 Comment(2)
Can you please elaborate on this? I'm sorry I could not followChadd
@Shikher, I did some experimentation and came up with a much better answer. Have a look!Further
N
1

When working within a project with a rake context (something like this) already defined:

describe 'my_method(my_method_argument)' do
  include_context 'rake'

  it 'calls my method' do
     expect(described_class.send(:my_method, my_method_argument)).to eq(expected_results)
  end
end
Natie answered 9/11, 2018 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.