ruby-on-rails - 如何使固定装置在 Rails 的测试中可更新?

标签 ruby-on-rails unit-testing fixtures

下面我列出了一些来自简单 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/

相关文章:

javascript - 如何生成 Jasmine 测试中使用的装置

ruby-on-rails - ruby 的 "any?"和 "all?"方法在空数组和哈希上的行为

ruby-on-rails - 晒干萝卜步骤定义

javascript - 如何将 fixture/*.json 文件中的特定记录访问到 cypress 中的特定测试用例中?

c++ - 我不想在使用 boost 库进行测试时发生访问冲突时停止测试

c# - Entity Framework 4.1 的假 DbContext 来测试我的存储库

unit-testing - XUnit 是否跨测试类共享 fixture 实例?

html - Ruby on Rails 未加载针对移动设备的响应式布局

sql - Rails 在 ActiveRecord::Relation 中使用 OR 进行搜索

java - Mockito when().thenReturn() 不能正常工作