0

所以我使用 Michael Hartl 的教程已经有一段时间了,我可以说它真的很有用,但是有一个问题,我猜这不是教程的一部分。因此,在“9.2.2 要求正确的用户”一章中,有一个测试用于检查用户是否不能访问其他用户的编辑页面,也不能提交直接的 PUT reauest。

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 ←[31mFailure/Error:←[0m ←[31mspecify { response.should redirect_to(root_path }←[0m←[31mExpected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>←[0m←[36m # ./spec/requests/authentication_pages_spec.rb:107:in `block (5 levels) in <top (required)>'←[0m

这是用户控制器:

class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update]
before_filter :correct_user,   only: [:edit, :update]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
end

def new
@user = User.new
end

def create
  @user = User.new(params[:user])
  if @user.save
    sign_in @user
    flash[:success] = "Welcome to the Sample App!"
    redirect_to @user
  else
    render 'new'
  end
end

def edit
end

def update
  if @user.update_attributes(params[:user])
    flash[:success] = "Profile updated"
    sign_in @user
    redirect_to @user
  else
    render 'edit'
  end
end

private

  def signed_in_user
    unless signed_in?
      puts "No user signed in"
    store_location
      redirect_to signin_path, notice: "Please sign in."
    end
  end

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

所以你可以看到问题是当使用 RSpec put 方法时,即使在检查正确的用户之前测试也会失败,因为它看到没有用户登录。这是一个很容易被忽略的小问题(不正确的用户不能直接PUT 请求)但对我来说这是一个难题,为什么它不能正常工作,而且我已经很长时间无法得到答案。

4

1 回答 1

2

看起来过滤器在触发signed_in_user前重定向回登录页面。correct_user这表明用户实际上并未通过sign_in userbefore 块中的调用正确登录。

您是否定义了 sign_in in spec/support/utilities.rb

include ApplicationHelper

def sign_in(user)
  visit signin_path
  fill_in "Email",    with: user.email
  fill_in "Password", with: user.password
  click_button "Sign in"
  # Sign in when not using Capybara as well.
  cookies[:remember_token] = user.remember_token
end
于 2012-06-05T11:29:00.640 回答