In Rails, how do you functional test a Javascript response format?

前端 未结 9 934
攒了一身酷
攒了一身酷 2021-01-31 15:41

If your controller action looks like this:

respond_to do |format|
  format.html { raise \'Unsupported\' }
  format.js # index.js.erb
end

and yo

相关标签:
9条回答
  • 2021-01-31 16:41

    Pass in a :format with your normal params to trigger a response in that format.

    get :index, :format => 'js'
    

    No need to mess with your request headers.

    0 讨论(0)
  • 2021-01-31 16:42

    RSpec 3.7 and Rails 5.x solution:

    A few of these answers were a little outdated in my case so I decided to provide an answer for those running Rails 5 and RSpec 3.7:

    it "should render js" do
      get :index, xhr: true
    
      expect(response.content_type).to eq('text/javascript')
    end
    

    Very similar to Steve's answer with a few adjustments. The first being xhr is passed as a boolean key/pair. Second is I now use expect due to should receiving deprecation warnings if used. Comparing the content_type of the response to be equal to text/javascript worked for me.

    0 讨论(0)
  • 2021-01-31 16:44

    Set the accepted content type to the type you want:

    @request.accept = "text/javascript"
    

    Combine this with your get :index test and it will make the appropriate call to the controller.

    0 讨论(0)
提交回复
热议问题