我有一个名为“Charity”的对象,我想确保每个慈善机构都有一个唯一的名称,不幸的是我得到了以下失败的测试,我怀疑这是我的工厂的问题:
Failures
1) Charity name is already taken
Failure/Error: it { @charity_with_same_name.should_not be_valid }
NoMethodError:
undefined method 'valid?' for nil:NilClass
...
慈善对象属于用户对象。这是charity.rb:
class Charity < ActiveRecord::Base
attr_accessible :name, :description, :summary
belongs_to :user
validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 40 }
validates :summary, presence: true, length: { maximum: 140 }
validates :description, presence: true
validates :user_id, presence: true
default_scope order: 'charities.created_at DESC'
end
以下是charity_spec.rb 的相关部分:
require 'spec_helper'
describe Charity do
let(:user) { FactoryGirl.create(:user) }
#before { @charity = user.charities.build(summary: "Lorem ipsum") }
before { @charity = user.charities.build(FactoryGirl.attributes_for(:charity)) }
# this makes sure that all the attributes for charity are set, whereas
#the previous code only sets the "summary" attribute
subject { @charity }
...
describe "name is already taken" do
before do
charity_with_same_name = @charity.dup
charity_with_same_name.name = @charity.name.upcase
charity_with_same_name.save
end
it { @charity_with_same_name.should_not be_valid }
end
...
这是 factory.rb:
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com" }
password "foobar"
password_confirmation "foobar"
...
factory :charity do
sequence(:name) { |n| "charity #{n}" }
sequence(:summary) { |n| "summary #{n}" }
sequence(:description) { |n| "description #{n}" }
end
end
我做错什么了?