使用 Minitest

问题描述

以下方法需要测试

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

如果该参数不为空,这是另一种确定记录创建方法的子方法

以下测试成功断言未创建记录

  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

但是这两个方法实例变量(这些没有写入数据库)导致了 nul 值,因此 assert_equal 断言是不可能的。

如何实现?

解决方法

@error_99_messages 属于控制器而不是测试,所以它为零。 (你可以检查@controller.error_99_messages,也许)

如果您的控制器要响应 @error_99_messages(如果参数无效),那么您应该通过 assert_match(或 assert_includesresponse.body

来测试错误
assert_includes 'id_at_chain missing',response.body
# or
assert_match /id_at_chain missing/,response.body

如果您重定向并将错误设置为 flash,则

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