在 Minitest 中测试更新操作

Testing update action in Minitest

我有测试 create:

  test "should create article" do
    assert_difference('Article.count') do
      post :create, article: {title: "Test", body: "Test article."}
    end
    assert_redirected_to article_path(assigns(:article))
  end

我想为 update 操作做这样的事情。

我的 update 操作如下:

  def update 
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

我正在考虑类似的事情:

  test "should update article" do
    patch :update, article {title: "Updated", body: "Updated article."}
  end

但我的问题是:如何检查我的文章是否在 Minitest 中更新了?以及如何找到我要更新的项目?在固定装置中,我有两篇文章。

您应该能够将您的一篇 fixture 文章分配给一个变量,并在文章 post-update 上进行 运行 断言,就像这样(我还没有测试过这段代码,它是只是为了说明测试结构​​):

test "should update article" do
  article = articles(:article_fixture_name)
  updated_title = "Updated"
  updated_body = "Updated article."

  patch :update, article: { id: article.id, title: updated_title, body: updated_body }

  assert_equal updated_title, article.title
  assert_equal updated_body, article.body
end

您可能希望在 setup 方法中将 article 初始化为实例变量,并在 teardown 方法中将其设置为 nil,或者您管理 setup/teardown 以确保您的起始状态在测试之间保持一致。