FactoryGirl / Rails:替换从模块调用的现有方法?

时间:2015-08-09 02:33:21

标签: ruby-on-rails rspec module factory-bot

我有几个包含模块EventTracker的类,后者又使用回调来记录事件。 EventTracker在每个类中调用my_config,它返回一个Hash,其中填充了在事件跟踪过程中要忽略的字段名称。

require 'event_tracker'

class User < ActiveRecord::Base

    EVENTS = Rails.application.config_for(:users)

    include EventTracker    

    def my_config
        EVENTS
    end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

这是模块:

module EventTracker

    extend ActiveSupport::Concern

  included do
    after_save :record_event
    after_destroy :record_destroyed
  end

    def get_change_fields
        attribute_names - my_config['exclude']
    end

    private

        def record_event
            changed = {}
            puts "my config is #{my_config}"
            self::changes.each do |key, val|
                changed[key] = val if get_change_fields().include? key
            end
            Event.record_event self, changed
        end

        def record_destroyed
            Event.record_event self, nil, 'destroy'
        end

end

这在控制台中正常工作并在服务器上运行,但是当我尝试运行必须创建用户登录的RSpec测试时,我在创建用户时遇到错误:方法{{1}在实例中调用get_change_fields时失败。我想这是因为该类没有加载和解析包含所需数据的yaml文件?

my_config

有没有办法让FactoryGirl在调用Failures: 1) CasesController should have a current_user Failure/Error: Unable to find matching line from backtrace TypeError: no implicit conversion of nil into Array # ./app/models/event_tracker.rb:11:in `-' # ./app/models/event_tracker.rb:11:in `get_change_fields' # ./app/models/event_tracker.rb:20:in `block in record_event' # ./app/models/event_tracker.rb:19:in `each' 时介入并提供哈希值?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方式:

#import <UIKit/UIKit.h>
@interface NSHMessagesView : UIView

@end

您可以在RSpec测试中为当前用户存根 let(:my_config) { exclude: 'exclude' } before do allow(subject).to receive_messages(my_config: my_config) end ,就像我在上面展示的那样。 如果有效,请告诉我。我可以根据您的输出更新答案。