Search code examples
ruby-on-railsrubyrspecautomated-testsrspec-rails

RSpec test not passing: Expected response to be a <3XX: redirect>, but was a <200: OK>


I have set the following test in my ads_controller.spec.rb file:

describe "ads#create action" do
    it "redirects to ads#show" do
      @ad = FactoryBot.create(:ad)
      expect(response).to redirect_to ad_path(@ad)
    end
end  

to correspond to this action in my ads controller:

def create
    @ad = current_user.ads.create(ad_params)
    redirect_to ad_path(@ad)
end 

Once an ad is created, I want it to redirect to the show page for the just created ad. While this works in my browser, I clearly haven't structured my test right since I get the following error:

Failure/Error: expect(response).to redirect_to ad_path(@ad)
   Expected response to be a <3XX: redirect>, but was a <200: OK>

I've tried to troubleshoot it for a while and not sure where I'm messing things up? Any ideas? Thanks!


Solution

  • You're not actually making a call to your create action. You have...

    describe "ads#create action" do
        it "redirects to ads#show" do
          @ad = FactoryBot.create(:ad)
          expect(response).to redirect_to ad_path(@ad)
        end
    end  
    

    Which is just using FactoryBot to create the ad. You need to do actual call to the post action.

    RSpec.describe AdsController, type: :controller do
    
      let(:valid_attributes) {
        ("Add a hash of attributes valid for your ad")
      }
    
      describe "POST #create" do
        context "with valid params" do
    
          it "redirects to the created ad" do
            post :create, params: {ad: valid_attributes}
            expect(response).to redirect_to(Ad.last)
          end
        end
      end
    end