【问题标题】:RSpec and active record validationsRSpec 和活动记录验证
【发布时间】:2021-04-10 21:33:29
【问题描述】:

我正在尝试验证电影的评分是否大于 0 且小于或等于 5,为此我在 RSpec 中使用“be_valid”,当我检查电影标题是否有效时为 nil,但它不适用于评级。

我不明白为什么

型号:

class Movie < ApplicationRecord
  validates :title, presence: true
  validates :rating, presence: true, numericality: { greater_than_or_equal_to: 0,less_than_or_equal_to: 5,  only_integer: true }
end

规格:

RSpec.describe Movie, type: :model do
  # checking model validations
  subject{described_class.new}

    it "title must be present" do
      subject.title = ""
      expect(subject).not_to be_valid
    end

    it "rating must be greater than 0" do
      subject.rating = 1
      expect(subject.rating).to be_valid
    end

    it "rating must be less than or equal to 5" do
      subject.rating = 5
      expect(subject.rating).to be_valid
    end
end

错误:

Movie
  title must be present
  rating must be greater than 0 (FAILED - 1)
  rating must be less than or equal to 5 (FAILED - 2)

Failures:

  1) Movie rating must be greater than 0
     Failure/Error: expect(subject.rating).to be_valid
     
     NoMethodError:
       undefined method `valid?' for 1:Integer
     # ./spec/models/movie_spec.rb:15:in `block (2 levels) in <top (required)>'

  2) Movie rating must be less than or equal to 5
     Failure/Error: expect(rating).to be_valid
     
     NameError:
       undefined local variable or method `rating' for #<RSpec::ExampleGroups::Movie:0x00007f8332f46fc0>
     # ./spec/models/movie_spec.rb:20:in `block (2 levels) in <top (required)>'

【问题讨论】:

    标签: activerecord rspec-rails


    【解决方案1】:

    您应该在其他 2 个测试用例中使用 expect(subject).to be_valid。您收到错误是因为您尝试验证 subject.rating 这是一个整数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多