所以我目前正在使用水豚和rspec做一些测试,我遇到了这个错误信息
用户验证失败:名字不能为空,姓氏不能为空,系统生成的密码不能为空水豚开始彪马...*版本3.11.4,代号:情歌*最小线程数:0,最大线程数:4*收听tcp://127.0.0.1:42509无法找到未禁用的可见字段“ first_name”创建一个新用户
下面是我的_form.html.haml代码:
panel-body
= simple_form_for @user do |f|
.form-inputs
.col-md-6
= f.input :first_name, label: I18n.t('user.first_name')
= f.input :middle_name, label: I18n.t('user.middle_name')
= f.input :last_name, label: I18n.t('user.last_name')
= f.input :username, label: I18n.t('user.username')
.col-md-6
- if current_user.role? "Administrator"
= f.input :user_role, label: I18n.t('user.role'), collection: User::ROLES, include_blank: false
- else
= f.input :user_role, label: I18n.t('user.role'), collection: User::ROLES, include_blank: false, disabled: true
= f.hidden_field :user_role
.col-md-12
.form-actions
- if @user.new_record?
= f.button :submit, I18n.t('user.create_user'), class: "btn btn-primary"
= link_to I18n.t('cancel'), users_path, class: "btn btn-default"
- else
= f.button :submit, I18n.t('user.update_user'), class: "btn btn-primary"
= link_to I18n.t('cancel'), user_path(@user), class: "btn btn-default"
这是我的功能测试(spec / features / users / create_user.rb):
require 'rails_helper'
RSpec.feature "Users", :type =>
:feature do
before do
begin
login_as(FactoryBot.create(:user, :admin)) # assumes you have a factory named `admin` that will create a user with the permissions to create other users
rescue StandardError => e
puts "#{e.message}"
end
end
it "Creates a new User" do
begin
visit "users/"
new_user = FactoryBot.build(:user)
fill_in "first_name", with: I18n.t('new_user.first_name') #new_user.first_name
fill_in "middle_name", with: I18n.t('new_user.middle_name')#new_user.middle_name
fill_in "last_name", with: I18n.t('new_user.last_name')#new_user.last_name
fill_in "username", with: I18n.t('new_user.username')#new_user.username
click_button "New User"
expect(page).to have_text "User was successfully created."
rescue StandardError => e
puts "#{e.message}"
end
end
end
下面是我的factoryBot
#spec/factories/users.rb
FactoryBot.define do
factory :user do
first_name { 'System' }
last_name { 'Administrator' }
username {'admin'}
password {'password'}
system_generated_password {'password'}
trait :admin do
user_role {"Administrator"}
end
end
end
您在Capybara甚至没有启动服务器之前就收到验证消息“用户验证失败:名字不能为空……”,这告诉我您的工厂没有产生有效的用户记录。您应该使用FactoryBot棉绒功能-https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#linting-factories-确保在运行测试之前所有工厂都产生有效的记录。您还需要研究使用序列-https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#sequences-用于工厂中具有唯一性要求的部分(例如username
),以便可以同时使用它创建两个或多个记录。
注意:不需要打包所有的begin ... rescue .. end
块-无论如何,任何出现的错误都会被打印出来,而通过抢救这些错误实际上是在防止有效的测试失败。