预期的响应是<重定向>,但是<200>。在Rspec的控制器测试中

时间:2016-10-06 11:38:28

标签: ruby-on-rails ruby 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会出现以下错误:

  

失败/错误:期望(响应).to redirect_to root_path          预期的响应为&lt;:redirect&gt;但是&lt; 200&gt;

我还检查了log / test.rb文件。重定向成功。但响应仍然是200而不是3xx:

  

[1m [36m(0.3ms)[0m [1mSAVEPOINT active_record_1 [0m
]     [1m [35mSQL(1.4ms)
  [0m INSERT INTO&#34;消息&#34; (&#34; body&#34;,&#34; sender_id&#34;,&#34; created_at&#34;,&#34; updated_at&#34;)VALUES($ 1,$ 2,$ 3,$ 4)返回&# 34; ID&#34; [[&#34; body&#34;,&#34; MyText&#34;],[&#34; sender_id&#34;,1],[&#34; created_at&#34;,&#34; 2016- 10-06 11:16:14.934487&#34;],[&#34; updated_at&#34;,&#34; 2016-10-06 11:16:14.934487&#34;]]
    [1m [36m(0.3ms)[0m [1mRELEASE SAVEPOINT active_record_1 [0m
]   重定向到http://test.host/
  在40ms内完成200 OK(ActiveRecord:5.9ms)     [1m [35m(0.6ms)[0m ROLLBACK

1 个答案:

答案 0 :(得分:3)

您使用xhr,因此它会200

尝试以下

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