gpt4 book ai didi

validation - Rails 4,rspec 3 : model validation test

转载 作者:行者123 更新时间:2023-12-04 00:35:03 27 4
gpt4 key购买 nike

我有一个 organization具有属性的对象 name, doing_business_as .我需要验证 namedoing_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"]

所以我知道功能在那里,但我无法进行可行的测试......

最佳答案

您需要使用 build 方法而不是 create 方法。

# 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")
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, name: "same-name", doing_business_as: "same-name")
expect(organization).to be_invalid
end
end

关于validation - Rails 4,rspec 3 : model validation test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27232358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com