Ruby on rails 为什么使用factory_girl进行rails测试?

Ruby on rails 为什么使用factory_girl进行rails测试?,ruby-on-rails,testing,factory-bot,Ruby On Rails,Testing,Factory Bot,我是rails测试的新手,所以我想知道使用名为factory_girl的gem进行测试的基本原理 目前我只使用RSpec。我的型号规格如下: require 'rails_helper' RSpec.describe User, type: :model do it 'creates user' do User.create(email: 'asd@we.com', password: 'asasdasdasd', admin: true, firstname: 'qwe'

我是rails测试的新手,所以我想知道使用名为factory_girl的gem进行测试的基本原理

目前我只使用RSpec。我的型号规格如下:

require 'rails_helper'

RSpec.describe User, type: :model do


  it 'creates user' do
      User.create(email: 'asd@we.com', password: 'asasdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.count).to eq(1)
  end

  it 'should not have password attribute' do

      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.attributes).to_not include('password')

  end

  it 'encrypts password' do
      User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 1)
      expect(User.first.encrypted_password).to_not eq('asdasdasd')
  end




end

在这段代码的上下文中,我期待着为测试集成factory_girl的基本原理。使用factory_girl是否会使此代码更加简洁明了?工厂女孩帮助解决哪些具体问题?我很欣赏你的见解。谢谢

工厂vs.夹具背后的理念是,您可以为特定的测试用例创建专用模型,而不是为各种目的维护一个稳定的模型

FactoryGirl和其他类似的工具使消除任意用户变得非常容易,比如您的代码可能会崩溃为:

it 'users can be created' do
  create(:user)
  expect(User.count).to eq(1)
end
然后,您可以自定义它,以使管理员或用户具有无效密码,或任何您可能需要的特定情况

我非常喜欢工厂,因为即使他们可以让你的测试稍微慢一点,但他们是自我清理的,这是一种方法,当删除时,不再让他们。固定装置常常以奇怪的工件结束,您不确定这些工件是否被使用,但移除它们会破坏测试,因为断言期望事情以特定的方式进行