Jerome
Jerome

Reputation: 6189

Assert value of an error message with Minitest

The following method requires testing

if params[:id_at_chain].blank?  
  @error_code_99 = true
  @error_99_messages = @error_99_messages + " id_at_chain missing. "
end

this is a sub-method to another method to determine the record creation if that param is not blank

The following test succeeds in asserting that the record is not created

  test "no id at chain" do
    assert_no_difference('Article.count') do
      post array_api_v1_articles_path, params: {
      "articles": [
        {
          "code": "000000000000000084",
          }
        ]
      }, as: :json
      puts @error_code_99
      puts @error_99_messages
      assert_equal(" id_at_chain missing. ", @error_99_messages)
    end
  end

But the two method instances variables (these are not written to the database) are resulting in nul values and thus the assert_equal assertion is not possible.

How can this be achieved?

Upvotes: 0

Views: 1265

Answers (1)

Lam Phan
Lam Phan

Reputation: 3811

@error_99_messages belongs to the controller not the test, so it's nil. (you can check @controller.error_99_messages, maybe)

if your controller's going to response @error_99_messages (if parameters invalid) then you should test the error by assert_match (or assert_includes) the response.body

assert_includes 'id_at_chain missing', response.body
# or
assert_match /id_at_chain missing/, response.body

in case you redirect and set error to flash, then

 assert_response :redirect
 assert_not_nil flash[:error]
 assert_match /your error message/, flash[:error]

Upvotes: 1

Related Questions