下面我列出了一些来自简单 Rails 应用程序的代码。下面列出的测试在最后一行失败,因为在这个测试中,帖子的 updated_at 字段在 PostController 的更新操作中没有改变。为什么?
这个行为在我看来有点奇怪,因为标准时间戳包含在 Post 模型中,本地服务器上的实时测试表明这个字段在从更新操作返回并且第一个断言得到满足后实际上被更新了因此它表明更新操作正常。
我怎样才能让 fixtures 可更新如上所说?
# 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(:one)
这意味着“在 posts.yml 中获取名为“:one”的 fixture 。这在测试期间永远不会改变,除非在正常测试中出现一些极其奇怪和破坏性的代码。
您要做的是检查 Controller 分配的对象。
post = assigns(:post)
assert post.updated_at.between?(before, after)
关于ruby-on-rails - 如何使固定装置在 Rails 的测试中可更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1402556/