我有一个组织对象具有属性名称,doing_business_as.我需要验证该名称与doing_business_as不同.
# app/models/organization.rb class Organization < ActiveRecord::Base validate :name_different_from_doing_business_as def name_different_from_doing_business_as if name == doing_business_as errors.add(:doing_business_as,"cannot be same as organization name") end end end
我有一个匹配的rspec文件来验证:
# spec/models/organization_spec.rb require "rails_helper" describe Organization do it "does not allow NAME and DOING_BUSINESS_AS to be the same" do organization = build(:organization,name: "same-name",doing_business_as: "same-name") expect(organization.errors[:doing_business_as].size).to eq(1) end end
当我运行规范,但是,它失败,这是我得到的:
$rspec spec/models/organization_spec.rb Organization does not allow NAME and DOING_BUSINESS_AS to be the same (Failed - 1) Failures: 1) Organization validations does not allow NAME and DOING_BUSINESS_AS to be the same Failure/Error: expect(organization.errors[:doing_business_as].size).to eq(1) expected: 1 got: 0 (compared using ==) # ./spec/models/organization_spec.rb:113:in `block (3 levels) in <top (required)>' Finished in 0.79734 seconds (files took 3.09 seconds to load) 10 examples,1 failure Failed examples: rspec ./spec/models/organization_spec.rb:110 # Organization validations does not allow NAME and DOING_BUSINESS_AS to be the same
我期待规范通过,并确保2个属性不能相同.在Rails控制台中,我可以模拟预期的行为,但我似乎无法使规范成功地“失败”.
我还通过Rails控制台检查它的工作原理:
$rails c > o = Organization.new(name: "same",doing_business_as: "same") > o.valid? => false > o.errors[:doing_business_as] => ["cannot be the same as organization name"]
所以我知道功能在那里,但我无法得到可行的测试…
解决方法
您需要使用构建方法而不是创建方法.
# spec/models/organization_spec.rb require "rails_helper" describe Organization do it "does not allow NAME and DOING_BUSINESS_AS to be the same" do organization = build(:organization,doing_business_as: "same-name") organization.valid? expect(organization.errors[:doing_business_as].size).to eq(1) end end
要么
# spec/models/organization_spec.rb require "rails_helper" describe Organization do it "does not allow NAME and DOING_BUSINESS_AS to be the same" do organization = build(:organization,doing_business_as: "same-name") expect(organization).to be_invalid end end