39
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでコントローラのprivateメソッドをテストする

Last updated at Posted at 2013-09-05

privateメソッドをテストしなくてはいけない、というのは行儀的には悪いことではありますが、必要に迫られた際にはRSpecのAnnonymousControllerという機能を使ってテストすることができます。

Ref: https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller

YourController#smartphone_view?というメソッドがprivateメソッドだとして、その返り値をテストしたい場合は、以下のように書くことができます。

describe YourController do
  describe '#smartphone_view?' do
    controller(YourController) do
      def index
        @result = smartphone_view?
        render text: 'ok'
      end
    end

    subject { assigns(:result) }
    
    context 'PCからのアクセス' do
      before do
        get :index
      end
      it { should be_false }
    end
    context 'スマホからのアクセス' do
      before do
        Rack::Request.any_instance.stub(:smart_phone?).and_return(true)
        get :index
      end
      it { should be_true }
    end
    context 'ガラケーからのアクセス' do
      before do
        Rack::Request.any_instance.stub(:mobile?).and_return(true)
        get :index
      end
      it { should be_true }
    end
  end
end

controllerメソッドの引数に、テスト対象のコントローラ名を入れるのがミソです。

39
32
1

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
39
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?