Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an object variable in rspec test but got nil

here is my rspec code:

describe User do
  before{(@user=User.new(username:"abcdefg",email:"[email protected]",password:"123456")}
  subject(@user)
  @user.save
end

and I got such an error : undefined method 'save' for nil:NilClass(NoMethodError)

I try to write the same code in the rails console,it just worked. But when it comes to Rspec,it failed and I'm not able to find any reason...

Could any one help me with it?

like image 865
Ryan Zhu Avatar asked Dec 15 '22 12:12

Ryan Zhu


2 Answers

here is the Rspec way:

describe User do
  let(:valid_user) { User.new(username:"abcdefg",email:"[email protected]",password:"123456") }

  it "can be saved" do
    expect(valid_user.save).to be_true
  end
end

Note that you should avoid database operations in your specs, it's what make them slow.

Another point, consider using factories to clean up your specs.

like image 101
apneadiving Avatar answered Dec 30 '22 08:12

apneadiving


You need to wrap the code in an example block (i.e., call the it method with a block), because in the context of the describe block, @user is not defined. For example:

describe User do
  before{(@user=User.new(username:"abcdefg",email:"[email protected]",password:"123456")}
  subject(@user)

  it "can be saved" do
    @user.should respond_to(:save)
    @user.save.should_not be_false
  end
end

Edit: I noticed also that you have subject(@user) but that may need to be a block in order to set it properly. The following is cleaner overall:

describe User do
  let(:user) { User.new(username:"abcdefg",email:"[email protected]",password:"123456") }

  it "can be saved" do
    user.should respond_to(:save)
    user.save.should_not be_false
  end
end
like image 39
Stuart M Avatar answered Dec 30 '22 08:12

Stuart M