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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With