Rails Rails 测试失败

xautjzd · 2013年08月28日 · 最后由 xautjzd 回复于 2013年08月29日 · 2262 次阅读

在学习《Rails Tutorials》9.2.2 节时,有一个测试一直没通过。错误如下图: 此测试是用户只能编辑自己的资料,如果试图编辑其他人的资料,则跳转到 root_path 对应的页面。不过不知为啥一直跳转到 signin 了。

测试代码如下:

describe "as wrong user" do                                                                                               
      let(:user) { FactoryGirl.create(:user) }                                                                                
      let(:wrong_user) { FactoryGirl.create(:user, email: "[email protected]") }                                                

      describe "visiting Users#edit page" do                                                                                  
        before { visit edit_user_path(wrong_user) }                                                                           
        it { should_not have_title(full_title("Edit user")) }                                                                 
      end                                                                                                                     

      describe "submitting a PATCH request to the User#update action" do                                                      
        before { patch user_path(wrong_user) }                                                                                
        specify { expect(response).to redirect_to(root_path) }                                                                
      end                                                                                                                     
    end         

controller 里面的逻辑是什么,上面提示是说 redirect 的路径不是 root_path 嘛。。

controller跳转没问题,我在浏览器中测试没问题,只是rspec测试没通过。User#update验证失败就会跳转到root_path

before_action :correct_user, only:[:edit, :update] 

def correct_user                                                                                                          
      @user = User.find(params[:id])                                                                                          
      redirect_to(root_path) unless current_user?(@user)                                                                      
end    

你测试里没登陆吧,当前用户都没有的,没有 current_userwrong_user 毫无意义,所以自然要引导你登陆先啦,没有登陆的 patch 等于耍流氓嘛,呵呵。

#3 楼 @nightire 我在 app/helpers/sessions_helper.rb 中定义了 current_user?的

#4 楼 @xautjzd 不不不,我不是说你没有定义 current_user 方法,而是说在你的测试里,current_user 没有值,也就是在测试环境里你没有用户登陆。

因为没有用户登陆,所以根本不能执行 patch,因为你的 patch 肯定是对 current_user 来操作的。没有登陆,就没有 current_userwrong_user 也就没有意义了。

再换句话说,之所以测试给出的结果是去到了 /signin,就是因为应用没有检测到有 current_user,因此它根本就没有去和 wrong_user 比较,而是直接让你登陆先。

为什么你人工测试成功了?因为你手动登陆了呀!你人工测试的时候在 development 环境下,此时你手动登陆的结果并不会让测试也共享到,因为测试运行在 test 环境下的。

所以,在你的测试里应该少了一句类似下面的东西:

before { sign_in user }

你去和教程对照一下看看是不是这样的?

正如 @nightire 分析的,请把你的测试和“代码 9.14”对比一下,看有什么不同。

#6 楼 @nightire 谢谢您到位的分析,确实少了before { sign_in user}

#7 楼 @andor_chen 谢谢您的中文翻译,目前正在阅读中

需要 登录 后方可回复, 如果你还没有账号请 注册新账号