2016-04-17 24 views
0

我正在測試可以包含在控制器中的模塊。 眼下的代碼看起來像這樣:動態添加方法之前(:全部)

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中添加模塊和索引方法。我想:

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 
    ........... 

正如我所用的before(:all)塊的@controller被定義爲<GithubAuthorizationController ...調試器看到。所以這是一個實例。運行代碼時也沒有錯誤,但測試失敗,因爲The action 'index' could not be found ...

我該怎麼做?我如何將代碼移動到before(:all)塊?由於

回答

2

在RSpec中做到這一點的方法是使用一個控制器塊:

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 

如果設置infer_base_class_for_anonymous_controllers爲false(這不是默認設置),那麼你需要做的controller(GithubAuthorizationController),否則你會直接繼承ApplicationController

您的問題可能是由於缺少路線 - controller助手會爲您創建一些路線(對於默認索引,顯示等)操作。你可以添加額外的例子與

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

嗨,很好的答案。我真的很想使用這個解決方案。但現在我得到'method_missing':未定義的方法'控制器'爲Class'.你有一個想法,爲什麼它失敗?你可以寄給我'controller do'的文件嗎?我無法找到它們。謝謝 –

+0

好吧,似乎與'control_class'一起工作。大。現在我得到'缺少路線'的錯誤。你會在哪裏添加'routes.draw {get「custom」=>「github_authorization#custom」}'block?在上下文中? –

+1

你可能需要在規範上輸入::controller,就像我剛剛添加的那樣。請參閱https://www.relishapp.com/rspec/rspec-rails/v/3-4/docs/controller-specs/anonymous-controller#draw-custom-routes-for-defined-controllers –