- Read Tutorial
- Watch Guide Video
In this guide, we are going to create a full name method for the User
model.
If you open schema.rb
, you'll see that we have a first name and a last name field. Even though you can call both these fields separately and combine them together in your view file, it's considered a better practice to implement a custom method to generate the full name
Let's start with our user_spec.rb
file and create a test case like this.
# spec/models/user_spec.rb describe "custom name methods" do it 'has a full name method that combines first and last name' do expect(@user.full_name).to eq("SNOW, JON") end end
Running rspec
now will obviously fail because we don't have a method called full_name
. Let's fix that by opening our user.rb
file, and defining a new method called full_name
.
If you run rspec
now, this should work and our test suite should be back to green.
Next, let's update our _post.html.erb
partial file. We'll change last_name
call to full_name
. Now, if you start the rails server and open the browser, this is what you'll see.