LoginSignup
67
62

More than 5 years have passed since last update.

Rake タスクをテストコードの中で複数回実行する

Last updated at Posted at 2012-09-21

Rake タスクをテストするとき、テストコード内で #invoke で呼び出すと、二回目の実行時に Rake タスクが実行されません。

describe 'hoge' do
  before(:all) do
    @rake = Rake::Application.new
    Rake.application = @rake
    Rake.application.rake_require("hoge", ["#{Rails.root}/lib/tasks"])
    Rake::Task.define_task(:environment)
  end

  describe "rake hoge" do
    context "Rake タスク実行後" do
      before do
        @rake["book:dismissed_suppliers"].invoke
      end

      it "hoge 一回目" do
        # Rake タスクが実行される
      end

      it "hoge 二回目" do
        # Rake タスクが実行されない
      end
    end
  end
end

これは仕様のようです。

もう一度実行したいときは Rake::Task#reenable というメソッドを実行する必要があります。

https://github.com/ruby/ruby/blob/trunk/lib/rake/task.rb#L155
https://github.com/ruby/ruby/blob/trunk/lib/rake/task.rb#L118

      before do
        @rake["book:dismissed_suppliers"].invoke
        reenable
      end

もしくは、#invoke ではなく、 #execute で呼び出すことで、テストコードのなかで二度 Rake タスクを実行することが可能になります。

      before do
        @rake["book:dismissed_suppliers"].execute
      end

特に理由がない限りは #execute で Rake タスクを呼び出す方が楽でいいと思います。

参考

こちらの記事のコメント欄が参考になります。

phil.sergi.blog: Testing Rake Tasks with RSpec

67
62
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67
62