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

我有一个组织对象具有属性名称,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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...