ruby-on-rails - FactoryGirl 传递 'nil' 而不是值

标签 ruby-on-rails rspec tdd factory-bot

我从 Rails 和 RSpec 开始,但在使用 FactoryGirl 时遇到了麻烦。基本上该对象不接收属性。

模型/用户.rb

class User < ActiveRecord::Base

    attr_accessor :name, :email, :show_name, :company, :identity, :password, :phone, :mobile
    validates_presence_of :name, :show_name, :email, :company, :identity, :password, :phone
    validates_uniqueness_of :email

end

规范/工厂.rb

FactoryGirl.define do
    factory :user do
        name "John Doe"
        email "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e3b3c3a14312c35392438317a3b2633" rel="noreferrer noopener nofollow">[email protected]</a>"
        show_name "John Doe"
        company "Company"
        identity "123.456.789-10"
        password "abc123"
        phone "1234-5678"
        mobile "1234-5678"
    end
end

Rails 控制台

irb(main):001:0> u = FactoryGirl.create(:user)
   (0.1ms)  BEGIN
  User Exists (0.3ms)  SELECT 1 FROM `users` WHERE `users`.`email` = BINARY '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c262324220c29342d213c202962233e2b" rel="noreferrer noopener nofollow">[email protected]</a>' LIMIT 1
  SQL (0.4ms)  INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
Mysql2::Error: Column 'company' cannot be null: INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
   (0.1ms)  ROLLBACK
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'company' cannot be null: INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

有人知道出了什么问题吗?

最佳答案

我认为你可能的意思是把 attr_accessible 而不是 attr_accessor

attr_accessible 是一个 Rails 函数,用于将字段列入白名单以进行批量分配。 attr_accessor 是一个 ruby​​ 函数,用于生成会干扰事物的 getter 和 setter。

关于ruby-on-rails - FactoryGirl 传递 'nil' 而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065016/

相关文章:

html - RoR 中的图像叠加

ruby-on-rails - 如何创建一个模型来记录 IPv4 和 IPv6 IP 地址以便在 Rails 3 中快速查找?

ruby-on-rails - 在 RoR 应用程序中使用 RSpec 进行测试 - 未初始化的常量

ruby-on-rails - rspec 如何使用 capybara 查询 html 正文电子邮件

reactjs - 错误 : Unable to find an element with the text when I try a test with Jest in React

sql - Postgres HStore 错误 - 未知运算符(operator)

ruby-on-rails - 有没有办法在rails控制台中撤消activerecord删除?

ruby-on-rails - 如何正确使用 stub 在rspec中进行测试

scala - 使用 TDD 学习 Scala

javascript - 为 TDD JavaScript 模拟用户输入