RailsでApplicationHelperのスペックを書くときにハマったのでメモ。
準備
まず普通にスペックを書く場合
spec/helpers/appliction_helper_spec.rbを以下のように準備
- require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
- describe ApplicationHelper, :type => :helper do
- helper_name :application
- %w{hoge}.each do |method_name|
- it "##{method_name}メソッドが存在すること" do
- helper.should be_respond_to(method_name)
- end
- end
- end
helper_nameでへルーパー名を定義しておくのがポイント。
そしてExampleの中から「helper」を通じて、エクスペクテーションを書いていきます。(言葉の使い方あってる?)
リクエストを使うスペックを書きたい場合
ヘルパーメソッドの中でリクエストを参照する場合(そもそもヘルパーがリクエストを参照するのが美しいことなのか疑問を抱きましたが、とりあえず無視)
ApplicationControllerにスタブアクションを作ってあげる、というやり方でなんとかしました。
- require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
- describe ApplicationHelper, :type => :helper do
- class ApplicationController
- def stub_action
- render :text => self
- end
- end
- helper_name :application
- it "ヘルパーの中からリクエストを参照できること" do
- get :stub_action
- helper.mobile_tracking_code.should be_xxxx
- end
- end
こんな感じで、普通にコントローラースペックを書くときのようにgetとかpostとかヘルパースペックの中からリクエストを使ったテストを一応かけます。
もっと良い方法がある気がする。