2012-02-03 50 views
5

考慮下面的代碼的類名:軌道/ Rspec的 - 寫作規範爲belongs_to的關聯

(1)你怎麼會寫一個規範來測試HOME_TEAM和AWAY_TEAM的類名應該是一個Team類?

(2)你是否應該編寫這樣的規範?我不確定我是否看到這樣做的價值,但想要得到您的想法。

class Event < ActiveRecord::Base 

    belongs_to :home_team, :class_name => 'Team', :foreign_key => :home_team_id 
    belongs_to :away_team, :class_name => 'Team', :foreign_key => :away_team_id 

end 

describe Event do 

    it { should belong_to(:home_team) } 
    it { should belong_to(:away_team) } 

end 

將是很好,如果早該有這樣的事情:

it { should belong_to(:home_team).with_class_name(:team) } 

回答

5

這裏是一個博客帖子爲什麼這真的是不應該做的:

http://blog.davidchelimsky.net/2012/02/12/validations-are-behavior-associations-are-structure/

總之,協會是你的應用程序的結構。 RSpec是爲了測試行爲。因此,如果您爲從home_team或away_team派生的行爲編寫測試,那麼它可能會更好。

例如,如果你想要home_team的名字。

def home_team_name 
    home_team.name 
end 

這是一種行爲,該事件類將索要HOME_TEAM:如果你寫了這樣的方法,這將是更好的。你可以寫一個規範,如:

describe '#home_team_name' do 
    before do 
    @home_team = Team.new(:name => 'The Home Team') 
    @event = Event.new(home_team_id: @home_team.id) 
    end 

    it 'should return the name of the home team' do 
    @event.home_team_name.should == 'The Home Team' 
    end 
end 

這將是測試協會的行爲,而不直接測試應用程序的結構的一個很好的例子。

另外,作爲一個觀點,Rails期望home_team是類「Team」,並且不需要測試框架,它已經過很好的測試和記錄。如果你需要提高你對協作工作方式的理解,我能看到做到這一點的唯一方法是暫時的。

+0

Heads Up:除非我做了'@home_team = Team.create(...'而不是'.new('因爲它看起來像AR直到它被保存時纔會給出一個id。 – afxjzs 2013-11-12 16:00:25

3

shoulda-matchers source來看,你應該能夠做到像...

it { should belong_to(:home_team).class_name(:team) } 

it { should belong_to(:home_team).class_name('Team') }