【问题标题】:Why does create from factory_girl throw error?为什么 create from factory_girl 会抛出错误?
【发布时间】:2017-06-10 11:07:15
【问题描述】:

当我不使用 factory_girl 时

我可以在我的 rspec 测试中创建对象

 u = User.create(email: 'as@wewe.com', password: 'asdqweqweqe', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w')
        expect(u.errors[:email]).to_not be_empty
   expect(u.errors[:role]).to_not be_empty

这样我可以检查验证错误,即

   expect(u.errors[:role]).to_not be_empty

但如果我使用工厂女孩

  factory :user_no_role, class: User do

    email 'asd@we.com'
    password 'asasdasdasd'
    admin true
    firstname 'qwe'
    lastname 'wer'
    grade 5
    section 'w'

  end


it 'role should be present' do
        u = create(:user_no_role)
        expect(u.errors[:role]).to_not be_empty
  end  

我收到以下错误

    User role should be present
     Failure/Error: u = create(:user_no_role)

     ActiveRecord::RecordInvalid:
       Validation failed: Role can't be blank

factory_girl 创建方法会抛出错误吗?如果是这样,我如何使用上面的 rspecs 测试验证错误?谢谢!

【问题讨论】:

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


    【解决方案1】:

    创建将引发验证异常,因为您试图立即保存它们。

    如果您只想构建一个,例如:

    u = User.new(...)
    
    u.valid? 
    => false
    
    u.errors # is not empty
    

    这也应该适用于FactoryGirl.build

    it 'role should be present' do
      u = build(:user_no_role)
      expect(u.errors[:role]).to_not be_empty
    end  
    

    顺便说一句:User.create 不会抛出异常 - 但 User.create! 会。

    请参阅ActiveRecord docs of create!FactoryGirl docs of build 了解更多信息。

    【讨论】:

    • u = build(:user_no_role) expect(u.errors[:role]).to_not be_empty 不起作用,我检查了 u.errors[:role].length 是 0 所以看起来像 build不会填充错误数组。如果是这种情况,我们如何验证错误数组?
    • 什么是u.valid?
    • 验证有效,但未填充错误。错误是否仅在创建时填充?
    • 有趣!这将失败 u = build(:user_no_role) expect(u.errors[:role]).to_not be_empty expect(u).to_not be_valid 但这会成功 u = build(:user_no_role) expect(u).to_not be_valid expect( u.errors[:role]).to_not be_empty
    • 看起来如果 valid 被第一次调用,那么它将填充错误数组,但如果我们首先检查数组,它将为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2019-06-13
    • 2021-06-17
    • 2015-02-25
    相关资源
    最近更新 更多