在before之前动态添加方法(:all)

时间:2016-04-17 09:55:35

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我正在测试可以包含在Controller中的模块。 现在代码看起来像这样:

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) - 块中添加模块和索引方法。我试过了:

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)块?感谢

1 个答案:

答案 0 :(得分: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