--A library that makes it easy to create data for testing --ʻUse Active Record`
If you install factory_bot_rails, you can create a file to create factory with the following command.
bin/rails g factory_bot:model task
I will explain a little.
Up to bin / rails g should be fine. Explicitly appear in the model with factory_bot: model. Please specify the target like task.
When you run this command, you should see a file like the following in spec / factories / tasks.rb.
spec/factories/tasks.rb
FactoryBot.define do
  factory :task do
  end
end
You have a template. Let's define the data in this.
spec/factories/tasks.rb
FactoryBot.define do
  factory :task do
    name "Shopping"
    content "Go buy supper"
  end
end
It may be less, but it should be okay. By executing FactoryBot.create (: task) in the test file, you can create the data described in spec / factories / tasks.rb.
For example, if you want to write an abnormal test that outputs an error when name of task is nil, you can write as follows.
spec/models/task_spec.rb
#Invalid if there is no name.
it "is invalid without a name" do
  task = FactoryBot.build(:task, name: nil)
  task.valid?
  expect(task.errors[:name]).to include("can't be blank")
end
By overwriting the property to nil, it looks as expected.
For example, the email address should be unique, it has such a specification, and you should write such a test. However, FactoryBot always refers to the same value, so it may not be possible to handle such an event.
This problem can be solved by using ** Sequence ** as shown below.
spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name "Yamada"
    sequence(:email) { |n| "test#{n}@example.com" }
  end
end
By defining it like this, it will be set as [email protected], [email protected].
Very convenient.
Recommended Posts