Rails3+RSpecでのテストを勉強してみる (4) - コントローラー及びヘルパーのテスト -

2012-09-09T00:00:00+00:00 rspec Ruby Rails

app/controllers/sample_controller.rb

class SampleController < ApplicationController
  def index
    if request.post?
      redirect_to :status => 404

      return
    end
  end
end

単純にPOSTメソッドでぶち込むと404になるようにする。

app/helpers/sample_helper.rb

module SampleHelper
  def say
    return content_tag(:h1, "hoge")
  end
end

まぁ機能自体使ってないけど。あくまでRSpecでテストする事だけが目的なので

spec/controllers/sample_controller_spec.rb

require "spec_helper"

describe SampleController do
  it "should be SampleController" do
    controller.should be_an_instance_of(SampleController)
  end

  it "requests GET /" do
    get "index"

    repsonse.should be_success
  end

  it "requests POST /" do
    post "index"

    response.should_not be_success
  end
end

コントローラーなテストな部分。GETで成功して、POSTで失敗するかだけをチェック

spec/helpers/sample_helper_spec.rb

describe SampleHelper do
  it "helper.say test" do
    helper.say().should == "<h1>hoge</h1>"
  end
end

,例えば、ApplicationHelperとSampleHelperに一つづつ機能付けて、RSpecでヘルパーをテストしようとすると両方helperで参照可能なのはなぜなんだろうと分からないのですが

まぁとりあえずこの件はほっとく

あとは普通どおりテストするコマンド投げれば良い

追記

コントローラーテストでcontrollerで参照できるはずなので、コントローラーにメソッド生やした場合はそれを介して出来るのはと思ったのだけど、例えば(あんまりやるべきでは無いとは思うのですが)コントローラーからViewHelperを参照して使った場合のテストってどうするんだろうと思ってたら、上記のままそんままSampleHelperをSampleControllerでincludeしちゃっても出来ない事が判明

class SampleController < ApplicationController
  include ActionView::Helpers::TagHelper
  include SampleHelper
end

あくまでcontent_tagとかが参照できないのでActionView::Helpers::TagHelperとかぶち込む必要がある模様。

あとは普通にコントローラーテスト側なcontrollerでメソッド参照すりゃ良いっぽい

foremanを使ってみる Rails3+RSpecでのテストを勉強してみる (3) - capybara-webkitを使ってみる -