【发布时间】: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_valid在recipe上调用方法:valid?。反过来,它将运行您在模型上定义的任何 Rails 验证。因此,您的代码 (您尚未向我们展示) 中的某些内容将引发该异常作为验证流程的一部分。 -
app/models/recipe.rb中有什么内容?你定义了什么验证?特别是引用ActiveSupport::MessageVerifier的代码在哪里? -
对,如果我去掉模型中图像的验证,测试成功。但是,我仍然希望拥有所需的图像。我可以在 RSpec 测试中上传图片吗?
标签: ruby-on-rails ruby rspec