我试过这段代码,但它引发了错误:NameError:未初始化的常量RSpec :: Mocks :: Mock RSpec::Mocks::Mock.stub(:i18n_scope).and_return(:activerecord)model = double(:model, errors: double(:errors, full_messages: []))ActiveReco
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类.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抛出的特定错误中解救!在某些情况下的方法.