未定义的方法`size'white shoulda-matcher和Rspec Rails

时间:2014-05-10 14:43:53

标签: ruby-on-rails ruby rspec factory-bot shoulda

我尝试使用should-matcher和Rspec以及FactoryGirls测试一个简单验证validate_presence_of但是当我运行时得到这个错误:

undefined method `size' for nil:NilClass

我的测试是:

context "when create new user" do
  let(:consumer) { create(:consumer) }

  it { should validate_presence_of(:name) }
end

在我的Consumer.rb中我有:

validates_presence_of :name, :email, :cpf, :phone_number, :birthday, :message => :attrs_blank,:on => :create

和我的FactoryGirls有:

FactoryGirl.define do
  factory :consumer do
    association :vendor
    association :branch
    association :client
    name { Faker::Name.name }
..

我尝试使用subject { FactoryGirl.create(:consumer) }代替let(:consumer) { create(:consumer) },但得到同样的错误,出了什么问题?

更新:

完成错误:

Consumer when create new user should require name to be set
     Failure/Error: it { should validate_presence_of(:name) }
     NoMethodError:
       undefined method `size' for nil:NilClass
     # ./app/models/consumer.rb:58:in `valid_phone?'

这个验证是问题所在:

validate :valid_phone?

显然这是问题,phone_numbernil

def valid_phone?
  @p = self.phone_number
  @bool = true
  if @p.size == 11 && @p[2] != "9"
    @bool = false
  elsif @p[0].eql?("0")
    @bool = false
  elsif @p.length > 11 || @p.length < 10
    @bool = false
  end
  errors.add(:phone_number,:error_phone) if @bool == false
end

我将测试修改为:

let(:consumer) { create(:consumer,:phone_number => "5182969611") }

但问题仍然存在。

0 个答案:

没有答案