2013-10-02 34 views
5

所以我正在寫一個rspec測試。它將測試模型是否重複正確。因此,規範是這樣的:我如何獲得一個模型的所有屬性減去幾個

it "should copy the data" do 
    @model = build(:model) 
    @another_model.copy_data(@model) 
    @model.data.should == @another_model.data 
    end 

的數據是一個嵌入的文檔,所以我這樣做時,它被複制。模型上的所有屬性都被成功複製,減去id和created_at日期。有沒有辦法像這樣做?

@model.data.attributes.without(:_id, :created_at).should == @another_model.data.attributes.without(:_id, :created_at) 

或者相反,我選擇所有其他字段沒有id和created_at?

謝謝!

回答

19

這工作

@model.attributes.except("id", "created_at").should == @another_model.attributes.except("id", "created_at") 
+0

非常好,謝謝 –

0

您可以這樣做,因爲.attributes會返回一個哈希值,其中每個鍵值對都是一個屬性及其值。

@model.data.attributes.each do |k,v| 
    next if k == 'id' || k == 'created_at' # Skip if the key is id or created_at 
    v.should == @another_model.data.attributes[k] 
end 
相關問題