4

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?

1
  • It may have worked for you in the console if you had already defined @user previously in the same session Commented Apr 3, 2013 at 7:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 as this is indeed a right answer like it is supposed to be done.
5

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

1 Comment

@user.save.should_not be_false to make it a true test ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.