2009-09-09 42 views
2

下面我列出了一些代碼,從簡單的Rails應用程序。下面列出的測試中最後一行失敗,因爲該職位的的updated_at場不PostController中的本次測試的更新操作中改變。爲什麼?如何在Rails的測試中更新燈具?

這種行爲在我看來有些奇怪,因爲標準時間戳包括在Post模型,本地服務器上現場測試表明,該領域是從更新的動作和第一個斷言回國後實際更新從而滿足它顯示了更新操作就OK了。

我怎樣才能使上面的意思燈具更新

# app/controllers/post_controller.rb 
def update 
    @post = Post.find(params[:id]) 
    if @post.update_attributes(params[:post]) 
    redirect_to @post  # Update went ok! 
    else 
    render :action => "edit" 
    end 
end 

# test/functional/post_controller_test.rb 
test "should update post" do 
    before = Time.now 
    put :update, :id => posts(:one).id, :post => { :content => "anothercontent" } 
    after = Time.now 

    assert_redirected_to post_path(posts(:one).id)  # ok 
    assert posts(:one).updated_at.between?(before, after), "Not updated!?" # failed 
end 

# test/fixtures/posts.yml 
one: 
    content: First post 

回答

4
posts(:one) 

,意思是「取名叫夾具‘:在posts.yml一個’這永遠不會在測試過程中改變,除非是在清醒測試沒有地方了一些非常奇怪的和破壞性的代碼。

你想要做的是檢查控制器分配對象

post = assigns(:post) 
assert post.updated_at.between?(before, after) 
+0

非常感謝你,這是我一直在尋找的解決方案! – 2009-09-09 23:59:56

1

在一個側面說明,如果你使用早該(http://www.thoughtbot.com/projects/shoulda/)它是這樣的:

context "on PUT to :update" do 
    setup do 
     @start_time = Time.now 
     @post = posts(:one) 
     put :update, :id => @post.id, :post => { :content => "anothercontent" } 
    end 
    should_assign_to :post 
    should "update the time" do 
     @post.updated_at.between?(@start_time, Time.now) 
    end 
end 

Shoulda很棒。

+0

確實。 Shoulda是很棒的東西。 – jdl 2009-09-10 01:09:56