使用 RSpec 测试模型时出现错误 "undefined method `<' for nil:NilClass"。
Error "undefined method `<' for nil:NilClass" when testing a model with RSpec.
我正在学习 RSpec 并测试以下场景:
require 'rails_helper'
RSpec.describe Student, type: :model do
before(:each) do
Student.delete_all
end
it "roll number can't be less than 0 or more than 80" do
s = Student.create(:name => "sanjay" , :lastname => "test" , :roll => 0)
s1 = Student.create(:name => "sanjay" , :lastname => "test" , :roll => 81)
expect(s).not_to be_valid
expect(s1).not_to be_valid
end
end
以下是 Student 模型定义:
class Student < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :roll
validate :number_of_valid_students
def number_of_valid_students
if (self.roll < 1) or (self.roll > 80)
self.errors.add(:rollnumber , "Can't be less than 0 or greater than 80")
end
end
end
在 运行 命令 rake spec:models
之后,我收到以下错误:
Failure/Error: expect(student).not_to be_valid
NoMethodError:
undefined method `<' for nil:NilClass
请帮忙。
谢谢。
您不需要添加自定义验证。考虑使用ActiveRecord提供的numericality validation:
class Student < ActiveRecord::Base
validates :name, presence: true
validates :roll, uniqueness: true
validates :roll, numericality: { greater_than: 1, less_than: 80 }
end
也这样写你的测试:
let(:student1) { Student.create(name: "sanjay", lastname: "test", roll: 0) }
let(:student2) { Student.create(name: "sanjay", lastname: "test", roll: 81) }
it "roll number can't be less than 0 or more than 80" do
expect(student1).not_to be_valid
expect(student2).not_to be_valid
end
查看 Better Specs 以获得 RSpec 最佳实践。
我正在学习 RSpec 并测试以下场景:
require 'rails_helper'
RSpec.describe Student, type: :model do
before(:each) do
Student.delete_all
end
it "roll number can't be less than 0 or more than 80" do
s = Student.create(:name => "sanjay" , :lastname => "test" , :roll => 0)
s1 = Student.create(:name => "sanjay" , :lastname => "test" , :roll => 81)
expect(s).not_to be_valid
expect(s1).not_to be_valid
end
end
以下是 Student 模型定义:
class Student < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :roll
validate :number_of_valid_students
def number_of_valid_students
if (self.roll < 1) or (self.roll > 80)
self.errors.add(:rollnumber , "Can't be less than 0 or greater than 80")
end
end
end
在 运行 命令 rake spec:models
之后,我收到以下错误:
Failure/Error: expect(student).not_to be_valid
NoMethodError:
undefined method `<' for nil:NilClass
请帮忙。 谢谢。
您不需要添加自定义验证。考虑使用ActiveRecord提供的numericality validation:
class Student < ActiveRecord::Base
validates :name, presence: true
validates :roll, uniqueness: true
validates :roll, numericality: { greater_than: 1, less_than: 80 }
end
也这样写你的测试:
let(:student1) { Student.create(name: "sanjay", lastname: "test", roll: 0) }
let(:student2) { Student.create(name: "sanjay", lastname: "test", roll: 81) }
it "roll number can't be less than 0 or more than 80" do
expect(student1).not_to be_valid
expect(student2).not_to be_valid
end
查看 Better Specs 以获得 RSpec 最佳实践。