【问题标题】:Undefined local variable or method params in RspecRspec中未定义的局部变量或方法参数
【发布时间】:2015-11-02 01:45:53
【问题描述】:

您好,我正在实施一种在我的 Web 应用程序中删除用户帐户的方法。我的控制器:

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>
    

我知道这个错误意味着什么,但我不知道如何纠正它。如何将用户 ID 从控制器传递给 rspec?

  1. 第二个错误是:

    Failure/Error: expect(response).to render_template(:home)
    expecting <"home"> but rendering with <[]>
    

我认为我的控制器方法有问题。它应该重定向到主页,但它没有。

【问题讨论】:

    标签: ruby-on-rails controller rspec-rails params


    【解决方案1】:

    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 模板没有呈现。

    【讨论】:

    • 其实我想确保模型方法接收到我当前用户的id,找出并删除它。在测试中,我可以返回一个 test_user 并删除它。但是如何测试我的模型方法是否接收到当前用户的 id?
    • 在这种情况下,您必须为您的测试实现用户登录,然后让您的用户在测试中登录,然后使用他的 id 删除用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多