我有一篇评论博客文章。控制器看起来像这样(删除了一些无关的东西):
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new comment_params.merge( user: current_user )
if @comment.save
redirect_to @comment.post and return
else
flash.now 'Comment Error'
redirect_to @comment.post and return
end
end
到目前为止,这么好。一切都按预期在浏览器中工作:当我提交的评论太短(触发验证错误)时,我收到了Flash消息并最终返回posts/show
页面。
但是,当我为同样的功能运行Rspec测试时,我的cookie和会话将被清除。当我回到posts/show
页面时,我已经退出并且没有闪光灯。不是我想要的。
这是失败的测试(在have_flash
行上失败):
scenario 'should not create a new comment if it is too short' do
sign_in @user
visit post_path(@post)
new_comment = 'too short'
within 'form#new_comment' do
fill_in 'comment_body', with: new_comment
click_on 'Comment'
end
expect(page).to have_flash 'Comment Error'
expect(page).not_to have_content new_comment
end
我知道为什么我的会话和cookie会在测试中重定向而不是在开发中被清除?