John Smith John Smith - 7 months ago 18
Ruby Question

Dynamically add method in before(:all)

Im testing a Module that can be included in a Controller.
Right now the code looks like that:

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


As you can see I basically create a Test-Controller before the tests are run. Now I would like to add the module and index method in the
before(:all)
-block. I tried:

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


As I can see in debugger in the
before(:all)
block the
@controller
is defined as
<GithubAuthorizationController ...
. So It is a instance. There Is also no error when running the code, but the tests fails, because of
The action 'index' could not be found ...


What do I wrong? How can I move the code to the
before(:all)
block? Thanks

Answer

The way to do this in rspec is with a controller block:

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

If you have set infer_base_class_for_anonymous_controllers to false (this is not the default) then you need to do controller(GithubAuthorizationController) or you'll inherit directly from ApplicationController

Your issue could be down to a missing route - the controller helper creates some routes for you (for the default index, show etc.) actions. You can add extra ones in an example with

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