LoginSignup
14
11

More than 5 years have passed since last update.

Rails MiniTestでlibとhelperテストのメモ

Posted at

Rails MiniTestでlibとhelperテストのメモ

Rails MiniTestでlibとhelperテスト時に少しつまったので、メモとして残しておきます。

libのテスト

まずRakefileに次の一行を追加します。
これでbundle exec rake testに含まれます。

Rakefile
:
MiniTest::Rails::Testing.default_tasks << 'lib'
:

次にテストコードです。
テストしたいlibをincludeしたオブジェクトを使います。

test/lib/xxx_test.rb
require "test_helper"

describe SampleLib do
  before do
    class TestSampleLib
      include SampleLib
    end
    @loader = TestSampleLib.new
  end

  describe "sampleを実行" do
    it "Sampleが返却される" do
      assert_equal 'Sample' @loader.sample
    end
  end
end

helperのテスト

libと同様に対象のhelperをincludeしたオブジェクトを使います。
button_toなどの他のhelperも使いたいのでActionView::Baseを継承します。

test/helpers/application_helper_test.rb
require "test_helper"

describe ApplicationHelper do
  before do
    class TestHelper < ActionView::Base
      include ApplicationHelper
    end
    @helper = TestHelper.new
  end

  describe "sampleを実行" do
    it "Sampleが返却される" do
      assert_equal 'Sample', @helper.sample
    end
  end
end
14
11
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
14
11