Home>
I want to achieve

Of the parent modeluserButhabitI have multiple child models.
habitTotaskThere is a column calleduserIshabitYou can have multiple models,taskI'm writing a test that doesn't allow duplicate columns.

ThereforeFactroyBotSame intaskHave a columnhabitI want to write a test that prepares two models, the first one succeeds in saving but the second fails.userThe email address already exists, probably because I try to create it twice.userWill result in a validation error.

I did some research on my own, but I couldn't find a way to do it.

If i can understand it, I would appreciate it if you could lend me your wisdom.
Thank you m (_ _) m

Error message
1) Habit validation user cannot save habit model with same task column
     Failure/Error: let (: habit2) {create (: habit2)}
     ActiveRecord :: RecordInvalid:
       Validation failed: Email address already exists


habit.rb

class Habit  = HABIT_MAX
        errors.add (: task, "can only be registered up to # {HABIT_MAX}")
    end
  end
end


FactoryBot

FactoryBot.define do
  factory: habit do
    task {"running"}
    frequency {3}
    user
  end
  factory: habit2, class: Habit do
    task {"running"}
    frequency {2}
    user
  end
end


habit_spec.rb

require'rails_helper'
RSpec.describe Habit, type :: model do
  let (: habit) {create (: habit)}
  let (: habit2) {create (: habit2)}
  describe'validation' do
    it'Cannot save if task is empty' do
      habit.task = ""
      expect (habit) .to_not be_valid
    end
    it'Cannot save if task is 12 characters or more' do
      habit.task = "a" * 13
      expect (habit) .to_not be_valid
    end
    it'user cannot save habit model with same task column' do # error location
        expect (habit.save) .to be_truthy
        expect (habit2.save) .to be_falsey
    end
    it "Cannot save if frequency is nil" do
      habit.frequency = nil
      expect (habit) .to_not be_valid
    end
  end
end
version

Rails 6.0.3.4
ruby 2.6.3p62
RSpec 3.10

  • Answer # 1

    User factory email addresssequenceIs it defined in?

    factory: user do
      sequence (: email) {| n | "tama # {n} @ cat.com"}
    end


    This way every time you build/create usernThe number of
    You can create a user with a unique email address.

    create (: user) .email # "[email protected]"
    create (: user) .email # "[email protected]"
    create (: user) .email # "[email protected]"

    factory_bot sequences