如何在 Rails 4 rspec 3.3.0 上存根 i18n_scope 以模拟 ActiveRecord::RecordInvalid? [英] How to stub i18n_scope for mocking ActiveRecord::RecordInvalid on Rails 4 rspec 3.3.0?

查看:46
本文介绍了如何在 Rails 4 rspec 3.3.0 上存根 i18n_scope 以模拟 ActiveRecord::RecordInvalid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have tried this code but it raises the error: 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?

推荐答案

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

To answer your question, you have to stub RSpec::Mocks::Double because that's the class of the instance you're actually passing to ActiveRecord::RecordInvalid. However, that won't work because RSpec::Mocks::Double doesn't implement .i18n_scope. So, what I did (and I hate it) was monkey-patch the RSpec::Mocks::Double class with a dummy method.

  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

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

But there's a better way of doing this by taking advantage of a block argument:

  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.

This way, you're testing much closer to your application data / logic vs. hacking RSpec.

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

This worked perfectly for a controller test where I was rescuing from a specific error that was thrown from an #update! method in certain situations.

这篇关于如何在 Rails 4 rspec 3.3.0 上存根 i18n_scope 以模拟 ActiveRecord::RecordInvalid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆