【问题标题】:Rspec for presence validation not working in Rails 5用于存在验证的 Rspec 在 Rails 5 中不起作用
【发布时间】:2018-07-02 06:16:02
【问题描述】:

模型待办事项

class Todo < ApplicationRecord
  has_many :items, dependent: :destroy
  validates :title, :created_by, presence: true
end

RSpecs

require 'rails_helper'

RSpec.describe Todo, type: :model do
  it { should have_many(:items).dependent(:destroy) }
  it { should validate_presence_of(:title) }
  it { should validate_presence_of(:created_by) }
end

当我运行命令bundle exec rspec 时,我看到了:

Finished in 1.82 seconds (files took 0.97238 seconds to load)
5 examples, 2 failures

Failed examples:

rspec ./spec/models/todo_spec.rb:8 # Todo should validate that :title cannot be empty/falsy
rspec ./spec/models/todo_spec.rb:9 # Todo should validate that :created_by cannot be empty/falsy

谁能解释为什么会失败?

【问题讨论】:

  • 您在 Todo 模型中有错字,validates :title, :created_by, presence: true 缺少逗号。
  • 已经修正了逗号,但这不是错误
  • 您的输出显示“5 个示例”,但我在您的代码中只看到 3 个。
  • 3 个来自一个模型,2 个来自这个模型,但问题出在这个模型上
  • 请阅读issue in shoulda

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


【解决方案1】:

这是shoulda-matchers 中的问题。您需要添加到您的spec_helper.rb

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多