3

我有一个基于 Active Record 的模型:- House

它有各种属性,但没有formal_name属性。但是它确实有一个方法formal_name,即

def formal_name
    "Formal #{self.other_model.name}"
end

如何测试此方法是否存在?

我有:

describe "check the name " do

    @report_set = FactoryGirl.create :report_set
    subject  { @report_set }
    its(:formal_name) { should == "this_should_fail"  }
end

但我明白了undefined method 'formal_name' for nil:NilClass

4

2 回答 2

3

首先,您可能想确保您的工厂在创建 report_set 方面做得很好——也许将 factory_girl 放在 Gemfile 中的开发组和测试组下,启动 irb 以确保它FactoryGirl.create :report_set不会返回 nil。

然后尝试

describe "#formal_name" do
  let(:report_set) { FactoryGirl.create :report_set }

  it 'responses to formal_name' do
    report_set.should respond_to(:formal_name)
  end

  it 'checks the name' do
    report_set.formal_name.should == 'whatever it should be'
  end
end
于 2012-07-12T17:01:24.647 回答
1

就个人而言,我不喜欢您使用的快捷方式 rspec 语法。我会这样做

describe '#formal_name' do
  it 'responds to formal_name' do
    report_set = FactoryGirl.create :report_set
    report_set.formal_name.should == 'formal_name'
  end
end

我认为这种方式更容易理解。


编辑:在 Rails 3.2 项目中使用 FactoryGirl 2.5 的完整工作示例。这是经过测试的代码

# model - make sure migration is run so it's in your database
class Video < ActiveRecord::Base
  # virtual attribute - no table in db corresponding to this
  def embed_url
    'embedded'
  end
end

# factory
FactoryGirl.define do
  factory :video do
  end
end

# rspec
require 'spec_helper'

describe Video do
  describe '#embed_url' do
    it 'responds' do
      v = FactoryGirl.create(:video)
      v.embed_url.should == 'embedded'
    end
  end
end

$ rspec spec/models/video_spec.rb  # -> passing test
于 2012-07-12T16:50:23.303 回答