简体   繁体   中英

How to trigger a JS controller action with Minitest

In a test I want to simulate a request that only accepts JS requests. I tried it in the "normal" style:

patch study_update_user_vocab_path(@user, @vocabs[index]), 
                                { strength: "1", resume_study_index: "index" }

Here, "strength" and "resume_study_index" are the ids of the form fields. When running the test I get the following error message:

 ActionView::MissingTemplate: ActionView::MissingTemplate: Missing template vocabs/study_update, application/study_update with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}.

This makes perfect sense, as there is no view to render. But how can I tell Mini:Test to trigger/expect JS?

I can think of two ways.

  1. In your routes, add defaults: { formats: 'js' } } to study_update_user_vocab_path. So it would be patch 'blah/path', to: 'controller#action', as: :study_update_user_vocab, defaults: { formats: 'js' } }

  2. In your test, write out the full path and add .js to the end. So patch "/users/#{@user.id}/vocabs/#{vocabs[index]}.js", { strength: "1", resume_study_index: "index" }

In controller tests you don't pass the path of the request to patch , you pass the action, which is the name of the method. I assume the method on your controller is update_user_vocab , so if I am wrong swap that out with the name of your method.

patch :update_user_vocab, id: @vocabs[index], # The record ID you are working with?
                          strength: "1", # I assume this is some needed query param
                          resume_study_index: "index", #same
                          format: "js" # send this as a js request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM