2010-10-08 47 views
0

我試圖在我的模型上測試方法。在控制檯中運行,但我的rspec測試不通過。結帳代碼:使用期望{}。更改,未通過,但在控制檯中工作

型號:

def import(master) 
    hsh = master.attributes.delete_if { |k,v| k == 'id' } 
    self.update_attributes(hsh) 
end 

Rspec的測試:

describe "#import" do 

    let(:master) { Factory(:sheet, :work_order => 'M1234', :sample_size => 10, :sample_scheme => 'TEST#') } 
    let(:wo) { Factory(:sheet, :work_order => 'W1234', :sample_scheme => 'ORIG#') } 

    it "imports all of the attributes from the master" do 
    expect { wo.import(master) }.to change(wo, :sample_scheme).to(master.sample_scheme) 
    end 

end 

我不知道這一點,這裏是輸出:

'Sheet#import imports all of the attributes from the master' FAILED 
sample_scheme should have been changed to "TEST#", but is now "ORIG#" 

正如我所說的,代碼正確地導入了屬性當在控制檯中運行時,它是主設備。這只是rspec測試失敗。我究竟做錯了什麼?


變化導入順便函數的結果:

def import(master) 
    hsh = master.attributes.delete_if { |k,v| k == 'id' } 
    hsh.each do |k,v| 
    self.update_attribute(k, v) 
    end 
    #self.update_attribute(:sample_scheme, hsh['sample_scheme']) 
    #self.update_attributes(hsh) 
end 

回答

0

問題是我的回調。出於某種原因,我正在刷新更新回調模型。不知道爲什麼我這樣做。這就解釋了爲什麼保存恢復正常,我的模型仍然像舊的一樣。感謝shingara的幫助。他讓我按照我需要的方式思考。

0

的變化的方法是不如果數據變化,使用,如果數量變化。你需要這樣的測試

describe "#import" do 

    let(:master) { Factory(:sheet, :work_order => 'M1234', :sample_size => 10, :sample_scheme => 'TEST#') } 
    let(:wo) { Factory(:sheet, :work_order => 'W1234', :sample_scheme => 'ORIG#') } 

    it "imports all of the attributes from the master" do 
    wo.sample_scheme.should.not == master.sample_scheme 
    wo.import(master) 
    wo.sample_scheme.should == master.sample_scheme 
    end 

end 
+0

我剛試過,但仍然失敗。這讓我感到很沮喪。這使我認爲它根本沒有更新,即使updat_attributes返回true。 – coreypurcell 2010-10-08 15:13:41

+0

爲了以防萬一,你可以在最後一句中重新加載嗎? – shingara 2010-10-08 15:51:41

+0

是的,我做到了。但這會變得陌生。查看帖子的編輯,在那裏我切換到使用update_attribute。我想知道爲什麼這會通過。我有一個before_update回調,但update_attributes返回true,所以它應該保存。 – coreypurcell 2010-10-08 15:53:05

相關問題