【问题标题】:mocking active record invalid exception with Rspec使用 Rspec 模拟活动记录无效异常
【发布时间】:2020-11-01 18:45:19
【问题描述】:

我正在模拟 rspec 中的活动记录无效异常。

这是我面临的问题的方法。 image_processing_error 检查图像对象的错误。

def save_image(image)
  begin
    image.save!
      { message: I18n.t("messages.image_saved") , status: 200 }
    rescue ActiveRecord::RecordInvalid
      image_processing_error(image)
  end
end

private

def image_processing_error(image = nil)
  if image && image.errors.any? && image.errors.messages.any?
    { message: image.errors.messages.values[0][0] , status: 422 }
  else
    { message: I18n.t("errors.invalid_request"), status: 422 }
  end
end 

这是我的 rspec 相同

# frozen_string_literal: true

require "rails_helper"

RSpec.describe ImagesService do
  describe ".save_image" do
    context "save image throws error" do
      let(:image) { double("image", { "errors": { "messages": { "name": ["is invalid", "must be implemented"]}}}) }

      before do
        allow(image).to receive(:save!).and_raise(ActiveRecord::RecordInvalid)
      end
      subject { described_class.save_image(image) }
      it "raised the error" do
        // I want to test the **ActiveRecord::RecordInvalid
        // I places NoMethodError to just pass the test
        expect { subject }.to raise_error NoMethodError
        expect { subject }.to raise_error ActiveRecord::RecordInvalid
      end
    end
  end
end

我在读取图像错误时遇到错误。什么是正确的双值,我必须让它工作。

Failures:

  1) ImagesService.save_image save image throws error raised the error
     Failure/Error: expect { subject }.to raise_error ActiveRecord::RecordInvalid
     
       expected ActiveRecord::RecordInvalid, got #<NoMethodError: undefined method `messages' for {:messages=>{:name=>["is invalid", "must be implemented"]}}:Hash> with backtrace:

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-5 rspec3


    【解决方案1】:

    在这种情况下,您在调用subject 时没有收到异常的原因是它没有引发异常。由于您在save_image 中设置了一个救援块,如果在其中引发异常,救援块将被调用并且异常不会传播给调用者,而是将调用image_processing_error。

    因此,在您的规范中,当您调用 subject 时,您不会收到异常,而是会从 image_processing_error 获得解析的错误,据我所知,这实际上是预期的行为。

    在这种情况下,您可以做的是测试您从subject 获得的结果是否与您在这种情况下获得的预期错误消息相匹配,例如:

    it "returns the error messages" do
        expect(response.body).to include("is invalid", "must be implemented")
    end
    

    【讨论】:

    • 这是有道理的。但我也看到使用的点语法可能不正确。 image_processing_error 实现对我来说似乎不正确,因为它有很多 .哈希的语法。例如,我从规范中粘贴的错误无法读取哈希。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多