【问题标题】:Assert value of an error message with Minitest使用 Minitest 断言错误消息的值
【发布时间】:2021-06-09 09:11:23
【问题描述】:

以下方法需要测试

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 断言是不可能的。

如何做到这一点?

【问题讨论】:

    标签: ruby-on-rails minitest


    【解决方案1】:

    @error_99_messages 属于控制器而不是测试,所以它是 nil。 (你可以检查@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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 2011-10-07
      • 2013-04-27
      相关资源
      最近更新 更多