gpt4 book ai didi

ruby-on-rails - 我如何指定 before_filters?

转载 作者:数据小太阳 更新时间:2023-10-29 08:14:55 33 4
gpt4 key购买 nike

我想用 rspec 指定我的 Controller before_filter。我想为此使用 ActionController::Testing::ClassMethods#before_filters。

我在我的 rails c 中得到了这些结果:

2.0.0p353 :006 > ActionController::Base.singleton_class.send :include, ActionController::Testing::ClassMethods
2.0.0p353 :003 > EquipmentController.before_filters

=> [:process_action, :process_action]

但实际上这是我行动的过滤器:

class EquipmentController < ApplicationController
before_filter :authenticate_user!

有什么想法吗?

最佳答案

这是我在我的项目中所做的:

# spec/support/matchers/have_filters.rb
RSpec::Matchers.define :have_filters do |kind, *names|
match do |controller|
filters = controller._process_action_callbacks.select{ |f| f.kind == kind }.map(&:filter)
names.all?{ |name| filters.include?(name) }
end
end

# spec/support/controller_macros.rb
module ControllerMacros
def has_before_filters *names
expect(controller).to have_filters(:before, *names)
end
end

# spec/spec_helper.rb
RSpec.configure do |config|
config.include ControllerMacros, type: :controller
end

然后您可以在 Controller 规范中使用它,例如:

# spec/controllers/application_controller_spec.rb
require 'spec_helper'
describe ApplicationController do
describe 'class' do
it { has_before_filters(:authenticate_user) }
end
end

关于ruby-on-rails - 我如何指定 before_filters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775737/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com