Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test helper method with Minitest

I would like to test a helper method using Minitest (minitest-rails) - but the helper method depends on current_user, a Devise helper method available to controllers and view.

app/helpers/application_helper.rb

def user_is_admin?                           # want to test
  current_user && current_user.admin?
end

test/helpers/application_helper_test.rb

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  test 'user is admin method' do
    assert user_is_admin?                # but current_user is undefined
  end
end

Note that I am able to test other helper methods that do not rely on current_user.

like image 960
user664833 Avatar asked Mar 05 '14 02:03

user664833


People also ask

How do you stub a method in Minitest?

Stubbing in Minitest is done by calling . stub on the object/class that you want to stub a method on, with three arguments: the method name, the return value of the stub and a block. The block is basically the scope of the stub, or in other words, the stub will work only in the provided block.

Does Minitest come with Ruby?

In this post, we will talk about Minitest, the standard software testing framework provided with Ruby. It isn't the only software testing framework available, but being supplied automatically with Ruby is a major advantage. In particular, we will discuss how to use Minitest assertions to test your software.

Does Rails Minitest?

Minitest is the default testing suite used with Rails, so no further setup is required to get it to work. Along with RSpec, it is one of the two most commonly used testing suites used in Ruby.


1 Answers

When you test a helper in Rails, the helper is included in the test object. (The test object is an instance of ActionView::TestCase.) Your helper's user_is_admin? method is expecting a method named current_user to also exist. On the controller and view_context objects this method is provided by Devise, but it is not on your test object, yet. Let's add it:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  def current_user
    users :default
  end

  test 'user is admin method' do
    assert user_is_admin?
  end
end

The object returned by current_user is up to you. Here we've returned a data fixture. You could return any object here that would make sense in the context of your test.

like image 71
blowmage Avatar answered Oct 11 '22 15:10

blowmage