7
3

More than 3 years have passed since last update.

helperのRSpecの書き方

Posted at

helperのテストの書き方を忘れるので、備忘録として投稿します。

以下のようにhelperに簡単なメソッドを用意して、テストを書いてみます。
helloというメソッドを実行すると、'hello'という文字列が返ってくる簡単なメソッドです。

app/helpers/posts_helper.rb
module PostsHelper
  def hello
    'hello'
  end
end

helperのspecファイルはspec/helpersに用意します。
手動でファイルを追加しても良いのですが、generateコマンドを実行すると自動で作成してくれるのでオススメです。

bin/rails g rspec:helper posts

helperのspecファイルを用意して、以下のように書いていきます。

spec/helpers/posts_helper_spec.rb
require 'rails_helper'

RSpec.describe PostsHelper, type: :helper do
  it 'hello' do
    expect(helper.hello).to eq('hello')
  end
end

typeがhelperになっています。
helper_specファイルでは、helperという変数を利用することができ、
helperに繋げてメソッドを実行することができます。

ちなみに、引数も取ることができます。

app/helpers/posts_helper.rb
module PostsHelper
  def plus100(num)
    num + 100
  end
end
spec/helpers/posts_helper_spec.rb
require 'rails_helper'

RSpec.describe PostsHelper, type: :helper do
  it 'plus100' do
    expect(helper.plus100(1)).to eq(101)
  end
end
7
3
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
7
3