Rails 4, rspec 3: validation du modèle de test

J'ai un organization objet dont les attributs name, doing_business_as. J'ai besoin de valider que la name n'est pas le même que 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

J'ai un correspondant rspec fichier qui vérifie ceci:

# 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

Quand je lance le spec, cependant, il échoue et c'est ce que j'obtiens:

$ 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

Je m'attendais à la spécification de passer et de s'assurer que les 2 attributs ne peuvent pas être les mêmes. Dans la console Rails je peux imiter le comportement attendu, mais je n'arrive pas à obtenir la spécification de "fail" avec succès.

J'ai aussi vérifié via la Console Rails qu'il fonctionne comme prévu:

$ 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"]

Donc je sais que la fonctionnalité est là, mais je ne peux pas obtenir un test réalisable...

OriginalL'auteur Dan L | 2014-12-01