使用rspec规范检查方法生成的值

时间:2014-10-20 17:41:49

标签: ruby-on-rails rspec

我们说我有一个Dog模型,它有一个Month_old的属性。而且我在模型中有一个方法可以像这样得到狗的年龄:

class Ticket < ActiveRecord::Base

  def age_in_years
    self.months_old / 12
  end

  def is_puppy?
    self.age_in_years == 0 ? true : false
  end
end

你想用Rspec测试方法,你的工厂看起来像这样:

FactoryGirl.define do 
  factory :dog do
    months_old   1
  end
end

你如何测试模型中的两个方法?这是我最好的猜测,但是当我尝试运行它时会抛出错误:

require 'spec_helper'

describe Dog do
  let(:dog) { FactoryGirl.create(:dog) }

  subject { dog }

  context "it's a puppy" do
    before do
      dog.months_old = 7
    end
    dog.age_in_years should equal(0)
    dog.is_puppy? should equal(true)
  end

end

错误类似于&#34;未定义的局部变量或方法`dog&#39;&#34;。

1 个答案:

答案 0 :(得分:0)

1您无需在DB中创建记录。你可以从内存中读取

2你的期望应该(必须)在it

例如

require 'spec_helper'

describe Dog do
  let(:dog) { Dog.new }

  context "it's a puppy" do
    before do
      dog.months_old = 7
    end

    it 'has 0 years' do
      dog.age_in_years should equal(0)
    end
    it 'returns true for `is_puppy`' do
      dog.is_puppy? should equal(true)
    end
  end
end

PS块名contextit的名称不好但与当前问题无关