如何使用补丁请求更新 Rails 中的布尔属性

How to update a boolean attribute in Rails using a patch request

我有一个布尔属性,我正在尝试使用 Rails 中的 Minitest 对其进行测试。这是有问题的测试:

test "admins can change a user's board member status" do
    patch user_path(@member, as: @admin), params: { user: { board_member: true } }
    assert_redirected_to(user_path(@member))
    assert_equal "Profile was successfully updated.", flash[:notice]
    assert_equal true, @member.board_member
end

我不明白为什么这不起作用。我可以在我的固定装置、数据库种子、浏览器中手动设置 board_member 属性为 true,也可以在 Capybara 的系统测试中设置。

我尝试使用 to_json 设置将用户参数传递给补丁请求,但这也不起作用。我一直收到相同的错误,就好像布尔属性没有切换到 true:

 test_admins_can_change_a_user's_board_member_status#UsersControllerTest (1.28s)
   Expected: true
   Actual: false

以下是我在用户控制器中将我的参数列入白名单的方式:

def user_params
   # List of common params
   list_params_allowed = [:email, :profile_photo, :first_name, :last_name, :title, :organization, :street, :city, :state, :zip_code, :phone]
   # Add the params only for admin
   list_params_allowed += [:role, :board_member] if current_user.admin?

   params.require(:user).permit(list_params_allowed)
end

同样,这在浏览器中按预期工作,但我想测试参数以确保在您尝试通过 url 提交“board_member”属性时没有安全漏洞.

您需要重新加载@member 以使其反映您的应用程序对数据库所做的更改。

test "admins can change a user's board member status" do
  assert_changes -> { @member.board_member }, from: false, to: true do
    patch user_path(@member, as: @admin), params: { user: { board_member: true } }
    @member.reload # get changes performed by app to db
  end
  # consider extracting this into separate examples
  assert_redirected_to(user_path(@member))
  assert_equal "Profile was successfully updated.", flash[:notice]
end