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