aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test/controller/required_params_test.rb
blob: 168f64ce417e18d0d7e7d710a2b0d753d14f89eb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'abstract_unit'

class BooksController < ActionController::Base
  def create
    params.require(:book).require(:name)
    head :ok
  end
end

class ActionControllerRequiredParamsTest < ActionController::TestCase
  tests BooksController

  test "missing required parameters will raise exception" do
    assert_raise ActionController::ParameterMissing do
      post :create, params: { magazine: { name: "Mjallo!" } }
    end

    assert_raise ActionController::ParameterMissing do
      post :create, params: { book: { title: "Mjallo!" } }
    end
  end

  test "required parameters that are present will not raise" do
    post :create, params: { book: { name: "Mjallo!" } }
    assert_response :ok
  end

  test "required parameters with false value will not raise" do
    post :create, params: { book: { name: false } }
    assert_response :ok
  end
end

class ParametersRequireTest < ActiveSupport::TestCase

  test "required parameters should accept and return false value" do
    assert_equal(false, ActionController::Parameters.new(person: false).require(:person))
  end

  test "required parameters must not be nil" do
    assert_raises(ActionController::ParameterMissing) do
      ActionController::Parameters.new(person: nil).require(:person)
    end
  end

  test "required parameters must not be empty" do
    assert_raises(ActionController::ParameterMissing) do
      ActionController::Parameters.new(person: {}).require(:person)
    end
  end

  test "require array when all required params are present" do
    safe_params = ActionController::Parameters.new(person: {first_name: 'Gaurish', title: 'Mjallo', city: 'Barcelona'})
      .require(:person)
      .require([:first_name, :title])

    assert_kind_of Array, safe_params
    assert_equal ['Gaurish', 'Mjallo'], safe_params
  end

  test "require array when a required param is missing" do
    assert_raises(ActionController::ParameterMissing) do
      ActionController::Parameters.new(person: {first_name: 'Gaurish', title: nil})
        .require(:person)
        .require([:first_name, :title])
    end
  end
end