Dengke Liu
Dengke Liu

Reputation: 141

Undefined method 'name=' for #<User:0x000000068e2078>

I am working on my rails project and writing rspec for one controller method.

I defined a method to delete the user account:

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

And here is my 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

In my factories, I already defined an object:

FactoryGirl.define do
factory :user do
    name                  "test"
    email                 "[email protected]"
    password              "foobar"
    password_confirmation "foobar"
end
end

Then I got the error:

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

for all three tests. How to solve this problem?

Upvotes: 0

Views: 1120

Answers (2)

Vinu Joseph
Vinu Joseph

Reputation: 975

FactoryGirl is now deprecated by FactoryBot.

FactoryBot version 5 onwards has deprecated static attribute assignment.

Hence the solution is to declare dynamic attributes while creating the factory.

So the solution is:-

FactoryBot.define do factory :user do name { "test" } email { "[email protected]" } password { "foobar" } password_confirmation { "foobar" } end end

Upvotes: 0

Anchalee
Anchalee

Reputation: 676

You should use User.first_name and User.last_name. There is no just name attribute.

FactoryGirl.define do
    factory :user do
        first_name            "test"
        last_name             "other_test"
        email                 "[email protected]"
        password              "foobar"
        password_confirmation "foobar"
    end
end

Upvotes: 3

Related Questions