My Rails Controller Spec is Not Passing When a Redirect Happens

25 Views Asked by At

I'm using rails 6 and ruby 3.1.1 and Rspec

It's been a minute since I've written tests, so the syntax is a bit new to me, but "I think" I understand it. A controller create test is not passing. It creates a new badge, then redirects to the badge show page. "I think" it is failing on the redirect. Debug code shows the record is saved, and a redirect_to is the next line.

I do not know what I need to change to make this work. Help?

# my app/controller

def create
  badge = LivingMuayThai::Badge.new(badge_params)
  if badge.save
    logger.info("@@@@@@@@@@@ badge controller create") # for debugging in test
    flash[:notice] = "You created a new Badge record"
    redirect_to(living_muay_thai_badge_path :id => badge.id)
  else
    flash[:notice] = "Creating that Badge did not work. hmmm!"
    render "new"
  end
end
# my controller spec

require 'rails_helper'
RSpec.describe LivingMuayThai::BadgesController, type: :controller do

  let(:valid_attributes) do
    {
     'badge_name'  => 'boxing 4 silver',
     'category'    => 'boxing',
     'color'       => 'silver',
     'number'      => 4,
     'image_name'  => 'boxing-4-silver.png',
     'sort_order'  => 4
    }
   end

  describe 'POST /create' do
    context 'with valid parameters' do
      it 'redirects to show badge' do
        post :create, params: { living_muay_thai_badge: valid_attributes }
        expect(response).to be_successful
      end
    end
  end

end

The error I'm getting is:

Failures:
  1) LivingMuayThai::BadgesController POST /create with valid parameters redirects to show badge
     Failure/Error: expect(response).to be_successful
       expected `#<ActionDispatch::TestResponse:0x00007fccb41e3268 @mon_data=#<Monitor:0x00007fccb41e31f0>, 
@mon_data_...equest=#<ActionController::TestRequest 
POST "http://test.host/living_muay_thai/badges" for 0.0.0.0>>.successful?` to be truthy, got false

     # ./spec/controllers/living_muay_thai/badges_controller_spec.rb:80:in `block (4 levels) in <top (required)>'

When I, tail -f log/test.log, I see the logger.info line I put in the app/controller, so I know the if badge.save is working. That makes me think something is happening on the redirect.

Am I missing something really obvious? Something in the syntax or structure of the test?

Thanks for any help!

1

There are 1 best solutions below

0
John Cowan On

I sort stumbled onto the answer. I was trying anything I could to get this to work and I just added .to be_redirect and it worked.

expect(response).to be_redirect

Hope this helps others.