Rails / Rspec:让匿名控制器属于某个类别

时间:2018-11-30 19:30:56

标签: ruby-on-rails ruby rspec rspec-rails

我的控制器从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。是否有可能让我的匿名控制器成为给定控制器的实例(在规范中声明)?

2 个答案:

答案 0 :(得分:1)

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

  

要指定其他基类,可以将该类显式传递给   控制器方法:

controller(BaseController)

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

因此您可以致电:

controller(RandomController)

根据您的规格

答案 1 :(得分:0)

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

<ListView ItemsSource="{Binding CompanyList}"
      IsGroupingEnabled="true" 
         HasUnevenRows="true">
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Status}" />
            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Margin="5" HorizontalOptions="Fill">
                    <Button Text="{Binding erpCode}"/>

                    <StackLayout HorizontalOptions="Fill">
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding name}"/>
                            <Label Text="{Binding statusReportDate}"/>
                        </StackLayout>
                        <Label Text="{Binding statusReportDescription}"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

您通常将此文件放在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