未定义的方法'name ='表示#<user:0x000000068e2078>

时间:2015-11-02 00:12:16

标签: ruby-on-rails rspec factory-bot

我正在研究我的rails项目并为一个控制器方法编写rspec。

我定义了删除用户帐户的方法:

class UsersController < ApplicationController

before_filter :set_current_user

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

def delete_account
    @user = User.find_by_id(params[:id])
    if @user.present?
        @user.destroy
    end
    flash[:notice] = "User Account Deleted."
    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[:user_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

在我的工厂里,我已经定义了一个对象:

FactoryGirl.define do
factory :user do
    name                  "test"
    email                 "test@example.com"
    password              "foobar"
    password_confirmation "foobar"
end
end

然后我收到了错误:

Failure/Error: @fake_results = FactoryGirl.create(:user)
 NoMethodError:
   undefined method `name=' for #<User:0x000000068e2078>

所有三项测试。如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您应该使用User.first_nameUser.last_name。没有name属性。

FactoryGirl.define do
    factory :user do
        first_name            "test"
        last_name             "other_test"
        email                 "test@example.com"
        password              "foobar"
        password_confirmation "foobar"
    end
end

答案 1 :(得分:0)

FactoryBot现在不推荐使用FactoryGirl。

FactoryBot版本5及更高版本已弃用静态属性分配。

因此解决方案是在创建工厂时声明动态属性。

因此解决方案是:-

FactoryBot.define do factory :user do name { "test" } email { "test@example.com" } password { "foobar" } password_confirmation { "foobar" } end end