Novneet Nov Novneet Nov - 2 months ago 29
Ruby Question

Expected response to be a <redirect>, but was <200> in Controller test in Rspec

I know a lot of other users have posted their problem with the same title. And I have tried all their solutions too. But despite trying everything, I
am unable to get to the solution.
So please don't downvote me. Here goes my problem:

The messages_controller_spec:

context 'with valid attributes' do
before :each do
user = FactoryGirl.create :user
sign_in user
end
it 'redirects to the root page' do
xhr :post, :create, messages: attributes_for(:message)
expect(response).to redirect_to root_path
end
end


Now My MessageController:

def create
@message = current_user.messages.build(message_params)
@recipients = User.all
if @message.save
redirect_to root_path, notice: "Message Sent!" #The test fails here
else
flash[alert] = "Great Scott!"
render :new
end
end


Running rspec from the console gives the following error:

Failure/Error: expect(response).to redirect_to root_path
Expected response to be a <:redirect> but was <200>

I have also checked the log/test.rb file. The redirection is successful. But the response is still 200 instead of 3xx:


[1m[36m (0.3ms)[0m [1mSAVEPOINT active_record_1[0m

[1m[35mSQL (1.4ms)

[0m INSERT INTO "messages" ("body", "sender_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["body", "MyText"], ["sender_id", 1], ["created_at", "2016-10-06 11:16:14.934487"], ["updated_at", "2016-10-06 11:16:14.934487"]]

[1m[36m (0.3ms)[0m [1mRELEASE SAVEPOINT active_record_1[0m

Redirected to http://test.host/

Completed 200 OK in 40ms (ActiveRecord: 5.9ms)
[1m[35m (0.6ms)[0m ROLLBACK

Answer

You use xhr so it give 200

Try Following

context 'with valid attributes' do
  before :each do
    user = FactoryGirl.create :user
    sign_in user
  end
  it 'redirects to the root page' do
    post :create, messages: attributes_for(:message)
    expect(response).to redirect_to root_path
  end
end