2016-04-17 1 views
0

コントローラに組み込むことができるモジュールをテストします。 は今のコードは以下のようになります。前に動的にメソッドを追加する(:all)

class GithubAuthorizationController < ApplicationController 
    include Frontend::Concerns::GithubAuthorization 

    def index 
    render inline: "lorem_ipsum" 
    end 
end 

describe GithubAuthorizationController do 
    before(:all) do 
    @page_content = "lorem_ipsum" 
    end 
    ........... 

あなたはテストが実行される前に、私は基本的にテスト・コントローラを作成する見ることができるように。今度はbefore(:all) -blockにmoduleとindexメソッドを追加したいと思います。私が試した:

class GithubAuthorizationController < ApplicationController 
end 

describe GithubAuthorizationController do 
    before(:all) do 
    @page_content = "lorem_ipsum" 

    class < @controller 
     include Frontend::Concerns::GithubAuthorization 

     def index 
     render inline: "lorem_ipsum" 
     end 
    end 
    end 
    ........... 

私は@controller<GithubAuthorizationController ...のように定義されてbefore(:all)ブロックにデバッガで見ることができるように。だからインスタンスです。コードを実行するとエラーは発生しませんが、テストは失敗します。The action 'index' could not be found ...

どうしますか?コードをbefore(:all)ブロックに移動するにはどうすればよいですか? RSpecの中でこれを行う方法のおかげ

答えて

2

は、コントローラブロックである:

describe GithubAuthorizationController, type: :controller do 
    context "with module" do 
    controller do 
     include Frontend::Concerns::GithubAuthorization 

     def index 
     render inline: "lorem_ipsum" 
     end 
    end 

    # within this block the controller will be the anonymous controller class created above 
    end 
end 

あなたは(これはデフォルトではありません)、あなたがcontroller(GithubAuthorizationController)を行う必要があるか、あなたがよfalseにinfer_base_class_for_anonymous_controllersを設定している場合ApplicationController

あなたの問題は、欠落しているルートになる可能性があります。controllerヘルパーは、(デフォルトのインデックス、showなどの)アクションをいくつか作成します。あなたは例で余分なものを追加することができます

it "does something with a custom route" do 
    routes.draw { get "custom" => "github_authorization#custom" } 
    get :custom 
    ... 
end 
+0

こんにちは、素晴らしい答えです。私は本当にこのソリューションを使用したいと思います。しかし、今は 'method_missing 'を取得しています:未定義のメソッド' Controller'はClass'です。なぜ失敗するのか考えていますか? 'controller do'のドキュメントを私に送ってもらえますか?私はそれらを見つけることができませんでした。ありがとう –

+0

Okは 'control_class'で動作するようです。すばらしいです。今、Imは 'missing routes'でエラーを出しています。どこに 'routes.draw {get" custom "=>" github_authorization#custom "}'ブロックを追加しますか?文脈で? –

+1

追加したばかりのように、spec:type:controllerが必要な場合があります。 https://www.relishapp.com/rspec/rspec-rails/v/3-4/docs/controller-specs/anonymous-controller#draw-custom-routes-for-defined-controllers –

関連する問題