Mocha模拟类方法包括before_filter

时间:2013-07-23 10:43:01

标签: ruby-on-rails rspec mocha

我正在尝试测试before_filter正在从关注中调用。我的测试看起来像这样:

class AuthorizableController < ApplicationController
  include Authorizable
end

describe Authorizable do
  let(:dummy) { AuthorizableController.new }

  it "adds a before filter to the class" do
    AuthorizableController.expects(:before_filter).with(:authorize)

    dummy.class_eval do |klass|
      include Authorizable
    end
  end
end

我的担心如下:

module Authorizable
  extend ActiveSupport::Concern

  included do
    before_filter :authorize
  end
end

...我收到一个看起来像这样的错误(没有提到mocha,而是MiniTest,当我使用RSpec时......):

Failures:

  1) Authorizable adds a before filter to the class
     Failure/Error: AuthorizableController.expects(:before_filter).with(:authorize)
     MiniTest::Assertion:
       not all expectations were satisfied
       unsatisfied expectations:
       - expected exactly once, not yet invoked: AuthorizableController.before_filter(:authorize)
     # ./spec/controllers/concerns/authorizable_spec.rb:11:in `block (2 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:0)

rails方法class_eval评估所讨论对象的单例类而不是具体类。在this question中有更多关于单例类的解释。因为过滤器正被添加到该单例类中,所以不满足在主类上调用authorize的期望。

您可以在dummy的单身人士课程中添加期望:

dummy.singleton_class.expects(:before_filter).with(:authorize)