我知道很多其他用戶已經發布了他們的問題,並且標題相同。我也嘗試了所有的解決方案。但儘管嘗試了一切,但我無法獲得解決方案。預期的響應是<redirect>,但是在控制器測試中是<200> Rspec
的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
現在我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
從控制檯運行RSpec的提供了以下錯誤:
Failure/Error: expect(response).to redirect_to root_path Expected response to be a <:redirect> but was <200>
我也查了日誌/測試.rb文件。重定向成功。但反應仍然是200,而不是爲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
感謝的人!這樣一個愚蠢的錯誤... –
是的,做到了。你能解釋一下在什麼情況下xhr會工作,爲什麼它不在這裏工作? –
@NovneetNov當你的請求是ajax請求時,你使用'xhr'。但在這裏你的請求不是Ajax請求。它簡單的發佈請求,並在成功後重定向到root_path。 –