1
votes

I'm learning Ruby. I'm now trying to test one of my controller.

My test file is myapp/test/testing.rb while my controller is located at myapp/app/controllers/test_controller.rb.

The content of testing.rb is

data = testController.mymethod()
puts(data)

But when doing

ruby myapp/test/testing.rb

in the terminal, I get a warning :

Traceback (most recent call last):myapp/test/testing.rb:6:in `': uninitialized constant testController (NameError)

Could someone explain me what i'm doing is wrong and how I should do this ?

Thanks !

2
why downvoted ? - gordie
Did you have a look at the official Rails Guides about Testing? - spickermann
"Could someone explain me how what i'm doing wrong" - pretty much everything. testController is most likely mispelt. mymethod is an instance method and not a class method. And finally this is not how you test controllers at all. - max
Ok, thanks. Well, I've got to learn somehow. Sorry to ask... - gordie

2 Answers

5
votes

The currently accepted way to test rails controllers is by sending http requests to your application and writing assertions about the response.

Rails has ActionDispatch::IntegrationTest which provides integration tests for Minitest which is the Ruby standard library testing framework. Using the older approach of mocking out the whole framework with ActionDispatch::ControllerTest is no longer recommended for new applications.

This is your basic "Hello World" example of controller testing:

require 'test_helper'

class BlogFlowTest < ActionDispatch::IntegrationTest
  test "can see the welcome page" do
    get "/"
    assert_select "h1", "Welcome#index"
  end
end

You can also use RSpec which is different test framework with a large following. In RSpec you write request specs which are just a thin wrapper on top of ActionDispatch::IntegrationTest.

1
votes

RSpec is DSL written on Ruby special for this purpose. You have to be familiar with it to write tests of your code. As for RSpec team note: `

The official recommendation of the Rails team and the RSpec core team is to write request specs instead. Request specs allow you to focus on a single controller action, but unlike controller tests involve the router, the middleware stack, and both rack requests and responses. This adds realism to the test that you are writing, and helps avoid many of the issues that are common in controller specs. In Rails 5, request specs are significantly faster than either request or controller specs were in rails 4.

So you have to write requestspecs for your controller. Something like this: spec/controllers/users_controller_spec.rb

RSpec.describe "Test", type: :request do
  describe "request list of all tests" do
    user = User.create(email: '[email protected]', name: 'Test User')
    get users_path
    expect(response).to be_successful
    expect(response.body).to include("Test User")
  end
end

Something like this. Hope it will help