【问题标题】:How to stub i18n_scope for mocking ActiveRecord::RecordInvalid on Rails 4 rspec 3.3.0?如何存根 i18n_scope 以在 Rails 4 rspec 3.3.0 上模拟 ActiveRecord::RecordInvalid?
【发布时间】:2015-10-09 11:28:35
【问题描述】:

我已经尝试过这段代码,但它引发了错误:NameError: uninitialized constant RSpec::Mocks::Mock

RSpec::Mocks::Mock.stub(:i18n_scope).and_return(:activerecord)
model = double(:model, errors: double(:errors, full_messages: []))
ActiveRecord::RecordInvalid.new(model)

我如何存根i18n_scope

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec stub rspec3


    【解决方案1】:

    要回答您的问题,您必须存根 RSpec::Mocks::Double,因为这是您实际传递给 ActiveRecord::RecordInvalid 的实例的类。但是,这行不通,因为RSpec::Mocks::Double 没有实现.i18n_scope。所以,我所做的(我讨厌它)是使用虚拟方法对 RSpec::Mocks::Double 类进行猴子补丁。

      it "does something cool" do
        foo = MyClass.new
        class RSpec::Mocks::Double
          def self.i18n_scope
            :activerecord
          end
        end
        error_double = double(:model, errors: double(:errors,full_messages: ["blah"]))
        expect(foo).to receive(:bar).and_raise(ActiveRecord::RecordInvalid, error_double)
        ...
      end
    

    但有一个更好的方法是利用块参数来做到这一点:

      it "does something cool" do
        foo = MyClass.new
        expect(foo).to receive(:bar) do |instance|
          instance.errors.add(:base, "invalid error")
          raise(ActiveRecord::RecordInvalid, instance)
        end
        ...
      end
    

    这样,您的测试更接近于您的应用程序数据/逻辑与黑客 RSpec。

    这对于控制器测试非常有效,我正在从 #update 引发的特定错误中解救出来!特定情况下的方法。

    【讨论】:

    • 好的@hlcs。需要详细说明吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多