jeudi 19 octobre 2017

Rspec testing model with null: false constraint

I am confused with testing (Rspec) a model with null: false on some attributes :

When creating a new instance with one of those attribute = nil, the new instance.valid? returns true but if I try to save it, it returns error messages on ActiveRecord::NotNullViolation. I understand it passes 'Model Validations' but fails in 'DataBase Validations'. What is a correct way to test my model then ?

RSpec.describe BusinessSetting, type: :model do
  # before :each do
  #   @business_setting = FactoryGirl.create(:business_setting)
  # end

  it "has a valid factory" do
    expect(FactoryGirl.create(:business_setting)).to be_valid
  end

  it "is invalid without a business_id" do
    expect(FactoryGirl.create(:business_setting, business_id: 
nil)).not_to be_valid
  end 

  it "is invalid without a bot_token" do
    expect(FactoryGirl.build(:business_setting, bot_token: nil)).to 
raise_error
  end  
end

ActiveRecord::NotNullViolation: Mysql2::Error: Field 'business_id' doesn't have a default value: INSERT INTO business_settings (bot_token, employee_user_id, created_at, updated_at, bill_regex, email, store_code, name, description) VALUES ('516dbe4b-9a54-47e7-be7f-9110703589e6', 25899, '2017-10-19 17:27:55', '2017-10-19 17:27:55', '^F947\d{7}$', 'email@magasin.com', '947', 'Nom du magasin', 'Description du magasin')

Aucun commentaire:

Enregistrer un commentaire