【问题标题】:Why RSpec throws an InvalidSignature error?为什么 RSpec 会抛出 InvalidSignature 错误?
【发布时间】:2020-08-18 15:27:59
【问题描述】:

我是 Ruby、Rails 和 TDD 的新手,但在测试代码时遇到了困难。 我正在尝试测试由使用 FactoryBot 创建的用户发布的 Recipe 模型的创建。

我的食谱模型 (app/models/recipe.rb) 是:

class Recipe < ActiveRecord::Base
  resourcify

  validates :image, presence: true
  validates :title, presence: true
  validates :preparazione, presence: true

  belongs_to :user
  has_many :likes
  has_many :comments

  has_one_attached :image
end

在 spec/models/recipe_spec.rb 我有:

require "rails_helper"

RSpec.describe Recipe, type: :model do
  describe "Creating a Recipe" do
    it "should be permitted" do
  
      @user = FactoryBot.create(:user)
      recipe = Recipe.new(title: 'Recipe', 
                          preparazione: 'Preparation',
                          image: '../support/test_image.jpg',
                          user_id: @user.id,
                          n_likes: 0,
                          n_comments: 0,
                          created_at: Time.now.utc)
      expect(recipe).to be_valid
      @user.destroy
    end
  end
end

此测试失败,错误为:

Failures:

1) Recipe Creating a Recipe should be permitted
 Failure/Error: expect(recipe).to be_valid

 ActiveSupport::MessageVerifier::InvalidSignature:
   ActiveSupport::MessageVerifier::InvalidSignature
 # ./spec/models/recipe_spec.rb:16:in `block (3 levels) in <top (required)>'

 Finished in 0.35273 seconds (files took 7.93 seconds to load)
 7 examples, 1 failure

 Failed examples:

 rspec ./spec/models/recipe_spec.rb:5 # Recipe Creating a Recipe should be permitted

为什么会出现这个错误,这是什么意思?

【问题讨论】:

  • 请给我们看Recipe模型类代码
  • expect(recipe).to be_validrecipe 上调用方法:valid?。反过来,它将运行您在模型上定义的任何 Rails 验证。因此,您的代码 (您尚未向我们展示) 中的某些内容将引发该异常作为验证流程的一部分。
  • app/models/recipe.rb 中有什么内容?你定义了什么验证?特别是引用ActiveSupport::MessageVerifier的代码在哪里?
  • 对,如果我去掉模型中图像的验证,测试成功。但是,我仍然希望拥有所需的图像。我可以在 RSpec 测试中上传图片吗?

标签: ruby-on-rails ruby rspec


【解决方案1】:
recipe = Recipe.new(title: 'Recipe', 
                          preparazione: 'Preparation',
                          image: Rack::Test::UploadedFile.new('spec/support/test_image.jpg', 'image/jpg')), 
                          user_id: @user.id,
                          n_likes: 0,
                          n_comments: 0,
                          created_at: Time.now.utc)

在 Rspec 中使用Rack::Test::UploadedFile class 上传附件。

【讨论】:

  • 它以image: Rack::Test::UploadedFile.new(Rails.root.join('spec/support/test_image.jpg'), 'image/jpg') 唤醒,谢谢!
  • 更新了答案。 Rack::Test::UploadedFile.new('spec/support/test_image.jpg', 'image/jpg')) 这应该也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2019-06-13
  • 2021-06-17
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多