简体   繁体   中英

Why don't I understand the Rails validates presence from tutorial?

I am following a Rails tutorial, and we created a user model, then were testing it with RSpec. In the spec/model/user_spec.rb we have:

require 'spec_helper'

describe User do

  before do
    @user = User.new(name: "Example User", email: "user@example.com")
  end

  subject { @user }

  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should be_valid }

  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end
end

When running the test it fails. When we add the following in the user model:

validates :name, presence: true

it passes. I understand that. What I don't understand is the use of this:

describe "when name is not present" do
before { @user.name = " " }
it { should_not be_valid }
 end

Isn't the validate presence enough?

After your edits, I think you are asking, "if we already checked that name is present to validate a record in the model class, why are we checking it again in a test?" The simple but not really clear answer is that the first part is checking that a user has a name, and the second part is testing that your application performs this check when actually presented with a new user.

The validates :name line is checking to see if a value for the name attribute is present; if not, Rails won't save the record when the save method is called on an instance of that model class, and it will generate an error message.

The spec is testing to validate that if you try to assign a blank or nil value to the attribute that must be validated ( name ), that Rails will not consider it valid, thus preventing it from being saved and triggering error messages.

There is an argument to be made that this is overkill as a test; in one sense you are just testing that functionality built into Rails (the validates method), which is presumably already tested there, is working as expected.

On the other hand, if you are writing the tests first and using them to describe the intended behavior of the User model, then you can argue that you are testing the application behavior associated with an attempt to create an invalid User to confirm it works as intended. I generally agree with this latter point of view.

The following line adds some validation to the User model:

validates :name, presence: true

This tells Rails that the name attribute must be present for an instance of the User model to be valid. If an instance of a model is not valid it cannot be saved ... and through this methodology you can prevent invalid records being saved.

As you progress through the tutorial this will begin to make more sense as you see the validation errors in the forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM