rspec - 如何测试不是数据库列的模型属性

时间:2012-07-12 16:40:11

标签: ruby-on-rails ruby rspec rspec-rails expectations

我有一个基于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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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