Failing rails test - ActionController::UnknownFormat:

817 Views Asked by At

I'm currently writing tests for all my controllers and have run into an issue I cannot solve. For one of my controllers, every test works (show, index, new, edit, update) but for some reason my #create test cannot pass. Just to clarify: all the fixtures and other methods run and pass fine - something is wrong with my create method or test on that method.

From what I can gather - the error may have something to do with the respond_to |format| line, but cannot seem to solve it.

Here's the test:

  test "should create captable" do
    sign_in @user
    post company_captables_url(@company, @captable), params: { captable: { company_id: @captable.company_id, name: "The BEST captable", version: @captable.version } }
    assert_response :success
  end

Here's the method from the controller:

  def create
      @captable = @company.captables.new(captable_params)

      respond_to do |format|
        if @captable.save
          format.html { redirect_to [@company, @captable], notice: 'Captable was successfully created.' }
          format.json { render :show, status: :created, location: @captable }
        else
          format.html { render :new }
          format.json { render json: @captable.errors, status: :unprocessable_entity }
        end
      end
    end

Error when running this test:

Error:
CaptablesControllerTest#test_should_create_captable:
ActionController::UnknownFormat: ActionController::UnknownFormat
    app/controllers/captables_controller.rb:24:in `create'
    test/controllers/captables_controller_test.rb:38:in `block in <class:CaptablesControllerTest>'


bin/rails test test/controllers/captables_controller_test.rb:36
 
1

There are 1 best solutions below

3
Igor Galvão On BEST ANSWER

From your controller, one can see it responds to both html and json.

However, in your test request, it's hitting the url without any format (see https://guides.rubyonrails.org/routing.html#path-and-url-helpers, there's no .anything at the generated urls or you'll find the .:format ending). So the controller does not know what to respond_to, throwing the Unknown Format error.

You essentially have a few options:

1) You can actually write the url and add an explicit format

2) You can try adding the format there with concatenation (ie: post "#{company_captables_url(@company, @captable)}.json")

3) You can set your routes to have a default response format (ie: resources :captables, defaults: { format: 'json' }). https://guides.rubyonrails.org/routing.html#defining-defaults