How to properly set a router variable during testing (minitest)?


#1

When I have a line:

get '/:quiz_id/quiz', to: 'quiz#testing' in apps/web/config/routes.rb

I can access this variable in the controller via params[:quiz_id].

How do I set this variable from minitest?

What I tried:

# test_spec.rb
describe 'something' do
  let(:params) { Hash[
    person: {
        sex: 'male'
      },
    'router.params' => { quiz_id: 1 }
    ]}
  it 'does something'
    action.call(params)
  end
end
...
# controllers/test.rb

module Web::Controllers::Quiz
  class Test
    include Web::Action

    def call(params)
      p(params)
    end
  end
end
...
# console output of running the test
<Hanami::Action::BaseParams:0x00561e08d9a748 
@env={:person=>{:sex=>"male"}, "router.params"=>{:quiz_id=>1}}, 
@raw={:quiz_id=>1}, 
@params={:quiz_id=>1}>
...
# console output of running the test BUT with commented 'router.params' => { quiz_id: 1 }
<Hanami::Action::BaseParams:0x00557d1d511770 
@env={:person=>{:sex=>"male"}}, 
@raw={:person=>{:sex=>"male"}}, 
@params={:person=>{:sex=>"male"}}>

Basically I can’t access any other parameters if I pass the router.params.

I also tried hacking it with rack.request.form_hash and rack.request.form_vars.


#2

Why don’t you just simply pass :quiz_id as a parameter to the action? As far as I know, actions don’t make any special distinction between “path” (“router”) params and other (query and body) params:

describe 'something' do
  let(:params) { Hash[
    person: {
        sex: 'male'
      },
    quiz_id: 1
    ]}
  it 'does something'
    action.call(params)
  end
end

#3

My concer was that when in production you pass the variable from router, it doesn’t get whitelisted by the params { required/optional } rules. But now when I think of it, I think you are actually right since I still want to validate this value. Thank you!