thornomad
thornomad

Reputation: 6777

How to test non-ActiveRecord models in rails?

How do I test a non-ActiveRecord model class in Rails? The code that works in the console does not seem to translate to the test suite. Methods are not available and the whole thing just doesn't seem to work!

class CalendarEvent

  def test
    'Hello World'
  end

end

When I fire up the console, this works:

irb> cal_event = CalendarEvent.new
=> #<CalendarEvent:0x007fb5e3ee9fd0>
irb> cal_event.test
=> "Hello World"

However, when I write a test it seems the model is not loading. None of the functions are available.

class CalendarEvent < ActiveSupport::TestCase
  include TestApiHelperPackage

  test 'validate hello world' do
    cal_event = CalendarEvent.new
    assert_equal cal_event.test, 'Hello world'
  end
end

Seems like it isn't grabbing the model. Do I have to not inherit from ActiveSupport::TestCase ?

Upvotes: 1

Views: 522

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

I am surprised that it even runs. You declare the class CalendarEvent in the test suit. Which obviously has no test method. Why would you name it the exact same way as the tested class? Just give it another name:

#                  ⇓⇓⇓⇓ HERE
class CalendarEventTest < ActiveSupport::TestCase
  include TestApiHelperPackage

  test 'validate hello world' do
    cal_event = CalendarEvent.new
    assert_equal cal_event.test, 'Hello world'
  end
end

And everything should go fine. Possible you want to require 'calender_event' in your test_heler.rb as well.

Upvotes: 4

Related Questions