我有一个organization
具有属性的对象name, doing_business_as
。我需要验证name
与 不同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
我期待规范通过并确保这两个属性不能相同。在 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"]
所以我知道功能在那里,但我无法获得可行的测试......