加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Rails 4,rspec 3:模型验证测试

发布时间:2020-12-16 22:44:23 所属栏目:百科 来源:网络整理
导读:我有一个组织对象具有属性名称,doing_business_as.我需要验证该名称与doing_business_as不同. # app/models/organization.rbclass Organization ActiveRecord::Base validate :name_different_from_doing_business_as def name_different_from_doing_busines
我有一个组织对象具有属性名称,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读