2012-07-12 47 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