2015-11-02 85 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删除用户。 –

    相关问题