Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I test controller method using rspec?

Tags:

I'm trying to learn rspec. I can't seem to test a rails controller method. When I call the method in the test, rspec just returns an undefined method error. Here is my test example

it 'should return 99 if large' do   GamesController.testme(1000).should == 99 end 

and here is the error:

 Failure/Error: GamesController.testme(1000).should == 99  NoMethodError:    undefined method `testme' for GamesController:Class 

I do have a testme method in the GamesController. I don't understand why the test code cannot see my methods.

Any help is appreciated.

like image 383
Randall Blake Avatar asked Apr 07 '12 04:04

Randall Blake


People also ask

How do I test a Rails controller?

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.

How do I run a test in RSpec?

Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.

What are controller tests?

Unit tests of controller logic. Unit tests involve testing a part of an app in isolation from its infrastructure and dependencies. When unit testing controller logic, only the contents of a single action are tested, not the behavior of its dependencies or of the framework itself.

Is RSpec TDD or BDD?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.


1 Answers

I think the correct way is this:

describe GamesController do   it 'should return 99 if large' do     controller.testme(1000).should == 99   end end 

In a rails controller spec, when you put the controller class in describe, you can use controller method to get an instance :P
Obviously, if testme method is private, you still have to use controller.send :testme

like image 107
Iazel Avatar answered Sep 25 '22 22:09

Iazel