2012-07-12 46 views
3

我有一个活动记录基于模型的模型属性: - 豪斯rspec的 - 如何测试这不是一个数据库列

它具有多种属性,但没有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

+1

的问题不在于formal_name是不存在的,问题是,你的'@ report_set'是'nil'。尝试将创建逻辑放在'let {}'块中 – DVG 2012-07-12 16:52:30

回答

3

首先你可能想确保你的工厂是做一个好工作创造report_set - 也许把factory_girl开发和测试组在你的Gemfile下,火了IRB确保那FactoryGirl.create :report_set不返回零。

然后尝试

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 
+0

我不会做'respond_to'测试。那时你正在测试ruby,那没有必要。但是作者公平地问了这个问题。 – Dty 2012-07-12 17:07:19

+0

这是我第一次写回应测试TBH。我只写了它,因为@ michael-durrant问它。 = P我同意他的问题很可能不是该方法的响应,而是他的工厂设置和/或定义。 – Wei 2012-07-12 17:15:35

+0

respond_to是唯一有效的部分。我确定respond_to(:junk)不起作用,而respond_to(:name)确实起作用。检查我无法使用这个或任何其他格式工作的值的简单测试。 – 2012-07-12 18:48:24

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 
+0

-1适用于ID(真实属性),但不适用于名称(虚拟属性)。我得到未定义的方法'name' – 2012-07-12 18:41:27

+0

@MichaelDurrant我使用工厂女孩2.5和工厂女孩轨道1.6,它绝对与虚拟属性一起使用。不知道为什么它不适合你。我添加了一个完整的例子,用测试代码 – Dty 2012-07-12 23:44:29