Jensky
Jensky

Reputation: 917

Testing update action in Minitest

I have test for 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

I want to do something like this for update action.

My update action looks like:

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

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

I am thinking about something like:

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

But I the problems: how to check is my article is updated in Minitest? And how to find item I am going to updated? In fixtures I have two articles.

Upvotes: 3

Views: 2787

Answers (1)

elements
elements

Reputation: 1057

You should be able to assign one of your fixture articles to a variable and run assertions on the article post-update, something like this (I haven't tested this code, it's just to illustrate the test structure):

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

You may want to initialize article as an instance variable in your setup method and set it to nil in your teardown method, or however you're managing setup/teardown to make sure your starting state stays consistent from test to test.

Upvotes: 2

Related Questions