attributes を持つ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
仕様が合格し、2 つの属性が同じであってはならないことを確認することを期待していました。Rails コンソールでは、期待される動作を模倣できますが、仕様を正常に「失敗」させることはできないようです。
また、Rails Console で期待どおりに動作することを確認しました。
$ 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"]
機能があることは知っていますが、実行可能なテストを取得できません...