RSpec和活动记录验证



我试图验证一部电影的评分是否大于0且小于或等于5,为此我使用";be_valid";在RSpec中,当我检查电影标题是否为零时,它似乎起作用,但对评级不起作用。

我不明白为什么

型号:

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)>'

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

最新更新