View tests fails when params used in template and in controller

Hello everyone!
My name is Paweł and i’m writing my first Hanami app :slight_smile:

So far so good, but i run into following 2 issues with tests for my controller and view.

First one, i have a route for form for nested resource, like /albums/:id/photos
In the template with list of photos i want to add link to new photo for album, using album_id from routing, from current URL

<a href="<%= routes.new_album_photo_path(params[:album_id]) %>">New photo</a>

This works in feature specs and in the application itself, however in view spec if fails:

     Failure/Error: let(:rendered)  { view.render }
       undefined local variable or method `params' for #<Hanami::View::Rendering::Scope:0x000055fbb93e6a10>

I have made a workaround for this in the test like this

  before do
    def view.params
      { album_id: 1 }

However, maybe someone will have other idea? I was thinking about using expose for this, but given that it works, and only tests fails, i decided for now that i prefer to hack tests, not logic :slight_smile: WDYT?

Second issue is also related to params, but this time in controller.
I wanted to use params[:album_id] for creating associated photo, like:

@photo =[:photo].merge(album_id: params[:album_id]))

This also works everywhere other than controller spec, where i get:

       SQLite3::ConstraintException: NOT NULL constraint failed: photo.album_id

regardless of the fact, that i have params in the test defined:

    let(:params) { Hash[album_id:, photo: { name: 'Photo1' }] }

Any ideas for this maybe also? :slight_smile:

@synu Hi and welcome :wave:

Params in view unit tests

A bit of background: params are available in development mode, and in integration tests, because they are provided by the corresponding Hanami Action.

When you test the view in isolation (without the Hanami Action), then you won’t have params available.

How to solve this?

You have the exposures Hash defined in the unit tests. Add anything you want to simulate data passed to the view.

To fix your spec:

let(:exposures) { Hash[format: :html, params: { id: 23 }] }

Params and repository

Are you able to tell me, which value returns the following line?

params[:photo].merge(album_id: params[:album_id])
1 Like

Thanks for your quick reply!
Ok, i managed to got both my problems fixed.

The first one, I surely got something messed up, i read the docs, i saw the part that i can pass params to exposures and i did tried that, but apparently did something wrong :slight_smile: Anyway - i managed to get this straight and it works, amazing :slight_smile:

The second issue i managed to narrow to being problem with params validation.
I have a validation like:

          params do
            required(:photo).schema do

And then params[:album_id] is nil. Once i added it to params it worked :slight_smile: Rails habbits :man_shrugging: :slight_smile:

Case closed, Thank You very much! :slight_smile:

1 Like