vendredi 11 décembre 2015

Can't get truncate method to pass test

I just started testing in rails and decided to begin with trying to test a truncate method in my Posts controller. It works perfectly fine when I call the method in my view. Just can't verify that it works in my test.

require 'test_helper'

class PostsControllerTest < ActionController::TestCase

  def setup 
    @post = Post.new(title: "Google", url: "www.google.com", category_id: 1, user_id: 1)
  end

  def truncate(title)
    if title.length > 110
      title = "#{title.first(90)}" + " ... (Click for more)"
    end
    return title
  end

  test "title should be truncated if it exceeds 110 characters" do
    @post.title = "a" * 115
    truncate(@post.title)
    assert title.length == 110
  end

end

Because I have set the truncate method to return title, I would have thought that I could write 'assert title.length == 110', but this returns me:

NameError: undefined local variable or method `title' for #<PostsControllerTest:0x007f8b948011d8>

I then decided to assign 'truncate(@post.title)' to new_title and ended up with this:

  test "title should be truncated if it exceeds 110 characters" do
    @post.title = "a" * 115
    new_title = truncate(@post.title)
    assert new_title.length == 110
  end

But this returns me:

Failed assertion, no message given.

I'm not even sure if i'm testing this correctly but if someone can point out what I'm doing wrong I would greatly appreciate it, thanks!

Aucun commentaire:

Enregistrer un commentaire