2015-11-02 89 views
-1

您好我正在實施一種方法來刪除我的Web應用程序中的用戶帳戶。我的控制器:Rspec中未定義的局部變量或方法參數

class UsersController < ApplicationController 

    before_filter :set_current_user 

    def user_params 
     params.require(:user).permit(:user_id, :first_name, :last_name, :email, :password, :password_confirmation) 
    end 

    def delete_account 
     @user = User.find_by_id(params[:id]) 
     if @user.present? 
      @user.destroy 
     flash[:notice] = "User Account Deleted." 
     end 
     redirect_to root_path 
    end 

    def destroy 
     User.delete(:user_id) 
     redirect_to root_path 
    end 
end 

我的RSpec的:

require 'spec_helper' 
require 'rails_helper' 
require'factory_girl' 

describe UsersController do 
    describe "delete account" do 

     before :each do 
      @fake_results = FactoryGirl.create(:user) 
     end 

     it "should call the model method that find the user" do 
      expect(User).to receive(:find).with(params[:id]).and_return (@fake_results) 
     end 

     it "should destroy the user account from the database" do 
      expect{delete :destroy, id: @fake_results}.to change(User, :count).by(-1) 
     end 

     it "should redirect_to the home page" do 
      expect(response).to render_template(:home) 
     end 

    end 
end 
  1. 第一個錯誤是

    Failure/Error: expect(User).to receive(:find).with(params[:id]).and_return (@fake_results) 
    
    NameError:undefined local variable or method `params' for #<RSpec::ExampleGroups::UsersController::DeleteAccount:0x00000007032e18> 
    

我知道這是什麼錯誤的手段,但我不知道如何糾正它。我如何將用戶標識從控制器傳遞給rspec?

  • 第二個錯誤是:

    Failure/Error: expect(response).to render_template(:home) 
    expecting <"home"> but rendering with <[]> 
    
  • 我認爲有什麼問題我的控制器方法。它應該重定向到主頁,但它不會。

    回答

    0

    params在您的測試中不可用,它可在您的控制器中使用。

    看起來你創建你的測試的測試用戶:

    @fake_results = FactoryGirl.create(:user) 
    

    然後,您可以使用此測試用戶的id@fake_results.id),而不是試圖用params[:id]

    expect(User).to receive(:find).with(@fake_results.id).and_return (@fake_results) 
    

    雖然,您可能想要將名稱從@fake_results更改爲更有意義的內容,例如test_user左右。

    但是,這應該解決你的兩個問題,因爲你的第二個問題在那裏,因爲第一個問題。由於無法首先刪除用戶,因此未將其重定向到根路徑,因此home模板未呈現。

    +0

    其實我想確保模型方法接收我當前用戶的ID,找到並刪除它。在測試中,我可以返回一個test_user並將其刪除。但是,我如何測試我的模型方法是否接收當前用戶的ID? –

    +0

    在這種情況下,您必須爲您的測試實施用戶登錄,然後讓用戶在測試中登錄,然後使用他的ID刪除用戶。 –

    相關問題