Ruby on rails 如何在Rails';测验?

Ruby on rails 如何在Rails';测验?,ruby-on-rails,unit-testing,fixtures,Ruby On Rails,Unit Testing,Fixtures,下面我列出了一些来自简单Rails应用程序的代码。下面列出的测试在最后一行失败,因为post的updated_at字段在此测试中在PostController的更新操作中没有更改。为什么? 这种行为对我来说似乎有点奇怪,因为标准时间戳包含在Post模型中,在本地服务器上的实时测试表明,在从更新操作返回后,该字段实际上被更新,并且第一个断言被实现,因此它显示更新操作正常 我怎样才能使装置在上述意义上可更新 # app/controllers/post_controller.rb def updat

下面我列出了一些来自简单Rails应用程序的代码。下面列出的测试在最后一行失败,因为post的updated_at字段在此测试中在PostController的更新操作中没有更改。为什么?

这种行为对我来说似乎有点奇怪,因为标准时间戳包含在Post模型中,在本地服务器上的实时测试表明,在从更新操作返回后,该字段实际上被更新,并且第一个断言被实现,因此它显示更新操作正常

我怎样才能使装置在上述意义上可更新

# 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
这意味着在posts.yml中“获取名为“:one”的fixture。这在测试过程中是不会改变的,除非一些在正常测试中没有位置的非常奇怪和破坏性的代码

您要做的是检查控制器正在分配的对象

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

另一方面,如果您使用的是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很棒。

非常感谢,这是我一直在寻找的解决方案!的确。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