Reputation: 804
I have a helper that truncates a user's full-name to only show their first name. I wrote a little test to just be sure that it works. I'm forcing myself to learn to test rigorously early on, so this may be overkill but I'm trying to learn a bit more about testing various aspects of the application.
application_helper.rb
module ApplicationHelper
def truncate_username(user)
@first_name = user.scan(/\A[a-zA-Z]+/).first
return @first_name
end
end
application_helper_test.rb require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
setup do
@usr = users(:travis)
end
test "First name should be truncated" do
assert_equal "Travis", truncate_username(@usr)
end
end
Every time I try to run this test I get a NoMethodError:
ERROR["test_First_name_should_be_truncated", ApplicationHelperTest, 0.7588860000250861]
test_First_name_should_be_truncated#ApplicationHelperTest (0.76s)
NoMethodError: NoMethodError: undefined method `scan' for #<User:0x007f9dcec71af0>
app/helpers/application_helper.rb:4:in `truncate_username'
test/helpers/application_helper_test.rb:11:in `block in <class:ApplicationHelperTest>'
Any ideas on why this is not working? Or perhaps how I could implement this test better.
Upvotes: 0
Views: 647
Reputation: 1677
scan
is a String method. You are passing your method a User
object, which does not have a scan
method (unless you define one).
To make it clearer, your method will work if you pass it a string. In this case, that's the user's full name.
def truncate_username(full_name)
@first_name = full_name.scan(/\A[a-zA-Z]+/).first
return @first_name
end
You could also consider putting this method directly on the User
model. If you define it something like
User.rb
def first_name
full_name.scan(/\A[a-zA-Z]+/).first
end
(replace full_name with whatever attribute you are storing the user's name to)
you could then instead be calling @user.first_name
in your application instead of truncate_username(@user.full_name)
.
Upvotes: 1