2

我试图通过将模块包含在基本的 mock_model 对象中来指定模块。但是,当我调用模块中定义的实例方法时,ActiveRecord 会尝试与数据库建立连接。

模块:

module Stuff
    module SoftDelete
        extend ActiveSupport::Concern

        def soft_delete
            puts "Called here"
        end
    end
end

规格:

describe Stuff::SoftDelete do
    class Network < ActiveRecord::Base
        include Stuff::SoftDelete
        attr_accessor :deleted_at
    end

    before (:each) do
        @network = mock_model(Network)
    end

    context "When a record is deleted" do
        it "is marked as deleted" do
            @network.soft_delete
        end
    end
end

当我运行此规范时,会发生以下错误:

  1) Stuff::SoftDelete When a record is deleted is marked as deleted
     Failure/Error: @network.soft_delete
     ActiveRecord::ConnectionNotEstablished:
       ActiveRecord::ConnectionNotEstablished
     # ./spec/apoc/soft_delete_spec.rb:18:in `block (3 levels) in <top (required)>'

注意:如果我在真正的 ActiveRecord 类中包含 SoftDelete 模块,它将起作用。似乎 mock_model 无法处理该模块。

希望对此有所帮助。谢谢!

4

1 回答 1

1

你信任 ActiveRecord 吗?如果是这样,请不要继承它;单独测试你的模块。如果您的模块包含调用 ActiveRecord 方法,请将它们存根并仅测试您的代码。

于 2012-05-01T03:53:03.973 回答