简体   繁体   中英

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

Failures:

  1) BusinessSetting is invalid without a business_id

Failure/Error: expect(FactoryGirl.create(:business_setting, business_id: nil)).to raise_error

 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:42:18', '2017-10-19 17:42:18', '^F947\\d{7}$', 'email@magasin.com', '947', 'Nom du magasin', 'Description du magasin')
 # ./spec/models/business_setting_spec.rb:14:in `block (2 levels) in <top (required)>'
 # ------------------
 # --- Caused by: ---
 # Mysql2::Error:
 #   Field 'business_id' doesn't have a default value
 #   ./spec/models/business_setting_spec.rb:14:in `block (2 levels) in <top (required)>'

  2) BusinessSetting is invalid without a bot_token

Failure/Error: expect(FactoryGirl.build(:business_setting, bot_token: nil)).to raise_error
       expected Exception but was not given a block
 # ./spec/models/business_setting_spec.rb:18:in `block (2 levels) in <top (required)>'

期望raise_error应该与{}一起使用

expect{FactoryGirl.create(:business_setting, business_id: nil)}.to raise_error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM