Rails/Rspec:拥有一个匿名控制器属于某个类



我的控制器从ApplicationController继承操作。我的目标是测试从ApplicationController继承的任何控制器的行为。为了实现这个目标,我在我的规范中创建了RandomController

这是我到目前为止的规格

require 'rails_helper'
RSpec.configure do |c|   
c.infer_base_class_for_anonymous_controllers = false
end
class RandomController < ApplicationController; end
class Random < ApplicationRecord; end
RSpec.describe RandomController, type: :controller do
controller {}
describe '.index' do
context 'when no record exists' do
before { get :index }
specify { should respond_with(200) }
end
end
end

这是application_controller

class ApplicationController
def index
binding.pry
end
end

问题是,当index方法运行时,self.class返回#<Class:0x00007f8c33b56fc8>而不是RandomController。有可能让我的匿名控制器是给定控制器的实例(在规范中声明(吗?

根据文档,您可以指定匿名控制器的基类:

要指定不同的基类,可以显式地将该类传递给控制器方法:

controller(BaseController)

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

因此,您可以调用:

controller(RandomController)

在您的规格

考虑使用shared_context而不是创建RandomController来测试共享代码:

shared_context 'an application controller' do
describe '#index' do
context 'when no record exists' do
before { get :index }
expect(response).to have_http_status(:ok)
end
end
end

您通常会将此文件放在/spec/support下。示例:

/spec/support/shared_contexts_for_application_controllers.rb

然后,在从ApplicationController继承的每个控制器中:

describe RandomController do
include_context 'an application controller'
end

最新更新