Hartl Rails教程测试在9.2.3节末尾失败

时间:2012-08-21 19:16:43

标签: ruby-on-rails rspec railstutorial.org

this section中,我应该限制用户仅编辑和更新自己的个人资料。我的所有测试都到了这一点,除了这一点:

     describe "as wrong user" do
       let(:user) { FactoryGirl.create(:user) }
       let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
       before { sign_in user }

       describe "visiting Users#edit page" do
         before { visit edit_user_path(wrong_user) }
         it { should_not have_selector('title', text: full_title('Edit user')) }
       end

       describe "submitting a PUT request to the Users#update action" do
         before { put user_path(wrong_user) }
         specify { response.should redirect_to(root_path) }
       end
     end

特别是最后一部分,重定向,这是我在运行测试时得到的结果:

  1) Authentication authorization as wrong user submitting a PUT request to the Users#update action 
     Failure/Error: specify { response.should redirect_to(root_path) }
       Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>
     # ./spec/requests/authentication_spec.rb:86:in `block (5 levels) in <top (required)>'

但是在网站上,当我尝试做同样的事情它工作得很好时,用户被重定向到应用程序的root_path。

2 个答案:

答案 0 :(得分:2)

我从your Github repo检查了您的代码,似乎您对 app / helpers / sessions_helper.rb 的修改是您失败测试的原因。将your filethe tutorial's file进行比较。您在方法中使用session哈希而不是cookies哈希。我通过更改代码修正了"submitting a PUT request to the Users#update action""submitting a DELETE request to the Users#destroy action"错误:

应用/助手/ sessions_helper.rb

module SessionsHelper
  # ...

  def sign_in(user)
    # session[:remember_token] = user.remember_token
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

  def sign_out
    self.current_user = nil
    # session.delete(:remember_token)
    cookies.delete(:remember_token)
  end

  def current_user
    # @current_user ||= User.find_by_remember_token(session[:remember_token])
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  # ...
end

Rails 3.0版本的The Rails Tutorial中有一个练习you replaced the cookies hash completely with a session hash,但我记得从来没有能够正确地做到这一点,而且doesn't seem to be in the 3.2 version无论如何,所以看起来你似乎是最安全地坚持使用此文件中的cookies哈希。

答案 1 :(得分:1)

代码清单9.6中的代码是用代码编写的吗?

# Sign in when not using Capybara as well.
cookies[:remember_token] = user.remember_token
  1. Capybara的行为类似于浏览器,因此它可以从rails app接收一些cookie。

  2. Capybara可以使用'fill_in'和'visit'来测试应用程序,例如操作浏览器。

  3. 要在Capybara发出“PUT / users / 1”请求,需要进入“/ users / 1 / edit”,然后点击“编辑”链接。 但是您的rails应用程序不允许用户访问其他用户,这在以前的测试示例中传递。

  4. 我们不能直接在Capybara发出“PUT / users / 1”。相反,我们需要使用“put”。 Rspec无法从应用程序接收任何cookie。因此我们需要将cookies设置为代码清单9.6。

  5. 如果测试示例在Cookie中没有remember_token的情况下发出“PUT / users / 1”请求,则会将其重定向为以非登录用户身份登录页面。但是这个测试意味着它被重定向到根页面,因为签名用户直接向其他用户的资源发送put请求。