RSpec 和活动记录验证
RSpec and active record validations
我正在尝试验证电影的评分是否大于 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)>'
您应该在其他 2 个测试用例中使用 expect(subject).to be_valid
。您收到错误是因为您正在尝试验证 subject.rating
这是一个整数。
我正在尝试验证电影的评分是否大于 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)>'
您应该在其他 2 个测试用例中使用 expect(subject).to be_valid
。您收到错误是因为您正在尝试验证 subject.rating
这是一个整数。