2010-10-19 87 views
1

我正在嘗試爲模型創建一個rspec測試。這個狀態模型與國家模型有關聯。我的工廠看起來像rspec與Factory Girl的模型關聯

Factory.define :country do |country| 
    country.name "Test Country" 
end 

Factory.define :state do |state| 
    state.name "Test State" 
    state.association :country 
end 

我已經做了功能狀態模型RSpec的,但我不知道我是否設置狀態@attr的方式是正確的或黑客

require 'spec_helper' 

describe State do 
    before(:each) do 
    country = Factory(:country) 
    @attr = { :name => 'Test State', :country_id => country.id } 
    end 

    it "should create a new state given valid attributes" do 
    State.create!(@attr) 
    end 
end 

作爲新軌道/ rspec我不確定是否強行說:country_id => country.id是正確的或解決問題的便宜方法。我感謝任何幫助或建議,我可以得到。

我也包括兩種模型以防萬一。

class Country < ActiveRecord::Base 
    has_many :states 
    attr_accessible :name 

    validates :name, :presence => true, 
        :uniqueness => {:case_sensitive => false} 
end 

class State < ActiveRecord::Base 
    belongs_to :country 

    attr_accessible :name, :country_id 

    validates :name, :presence => true, 
        :uniqueness => {:case_sensitive => false, :scope => :country_id} 

    validates :country_id, :presence => true 
end 

回答

2

這是一個好的開始,但是您的測試實際上並沒有測試任何東西。一般來說,每個「it」塊應該總是有一個「應該」調用。

下面是看着它,假設同一廠家和型號的另一種方式:

require 'spec_helper' 

describe State do 
    before(:each) do 
    @state = Factory.build(:state) 
    end 

    it "should create a new state given valid attributes" do 
    @state.save.should be_true 
    end 
end 
+0

謝謝,現在的偉大工程! – rrivas 2010-10-20 00:27:51