我正在为项目编写一些模型。我有一个User.rb
类,它具有以下属性:
- first_name:string
- last_name:string
- address_line_1:string
- address_line_2:string
- town:string
- post_code:string
- tel_no:string
- 电子邮件:字符串
- password_digest:string
- 类型:
我有第二个模型Employee.rb
,它继承自User.rb
。
User.rb
和Employee.rb
都是搭建的。 User
首先被搭建,Employee
搭建了--parent=User
选项。
运行测试时,出现以下错误:
Failure:
EmployeesControllerTest#test_should_create_employee [filepath]:
"Employee.count" didn't change by 1.
Expected: 3
Actual :2
这是在employees_controller_test中失败的代码:
setup do
@employee = employees(:employee_one)
end
test "should create employee" do
assert_difference('Employee.count') do
post employees_url, params: { employee: { first_name: @employee.first_name, last_name: @employee.last_name, address_line_1: @employee.address_line_1, address_line_2: @employee.address_line_2, town: @employee.town, post_code: @employee.post_code, tel_no: @employee.tel_no, email: @employee.email, password_digest: "@employee.password_digest", type: @employee.type } }
end
assert_redirected_to employee_url(Employee.last)
end
以下是我的员工工具,在employees.yml
employee_one:
first_name: "Employee1"
last_name: "Example"
address_line_1: "3 High Street"
address_line_2: "Flat 3"
town: "Glasgow"
post_code: "G15 9BL"
tel_no: "0123847439"
email: "employee1@employee1.com"
password_digest: "password"
type: "Employee"
我想我的User.rb
也很重要,包括:
class User < ApplicationRecord
validates :first_name, presence: true, length: { maximum: 50 }
validates :last_name, presence: true, length: { maximum: 50 }
validates :address_line_1, presence: true, length: { maximum: 50 }
validates :address_line_2, presence: true, length: { maximum: 50 }, :allow_nil => true
validates :town, presence: true, length: { maximum: 50 }
validates :post_code, presence: true, length: { maximum: 10 }
validates :tel_no, presence: true, length: { maximum: 14 }
validates :email, presence: true, length: { maximum: 50 }
validates :password_digest, presence: true, length: { maximum: 256 }
validates :type, presence: true, length: { maximum: 15 }
end
我已经在这里待了4个小时左右,我想我只需要一双新眼睛。
如果我继续使用rails console --sandbox
并使用User.create单独输入2个用户,并单独输入2名员工,则没有问题。
创建错误的原因是什么?
答案 0 :(得分:0)
使用employee.rb
选项支持--parent=User
模型,不会自动将继承的参数从user.rb
添加到employee.rb
。
这意味着在employees_controller.rb
中,employee_params
方法定义了允许的参数:
def employee_params
params.require(:employee).permit(:type)
end
这意味着当测试在Employees表中创建一个条目时,除了type
之外的所有参数都没有插入。
我通过将employee_params
更改为:
def employee_params
params.require(:employee).permit(:first_name, :last_name, :address_line_1, :address_line_2, :town, :post_code, :tel_no , :email, :password_digest, :type)
end
现在所有测试都通过了。