0

だから私はしばらくの間、Michael Hartl のチュートリアルを使用してきました。これは本当に便利だと言えますが、問題があり、チュートリアルの部分ではないと思います。そのため、「9.2.2 適切なユーザーの要求」の章では、ユーザーが他のユーザーの編集ページにアクセスしたり、直接 PUT 再試行を送信したりできないことを確認するためのテストがあります。

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前にフィルターがサインイン ページにリダイレクトしているようです。これは、ユーザーがbefore ブロックの呼び出しcorrect_userによって実際に正しくサインインしていないことを示唆しています。sign_in user

sign_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 に答える