Rails testing - Stubs and mocks - ruby-on-rails-3

I am working on a rails project, in which model queries a service and gets the data from the service. Now, when I want to write tests for models and controllers I need to imitate the service.I am fairly new to rails testing. I am confused as to what I should do. Rails has stubs, mocks and fixture - which of the three should I use. I suppose fixtures wont be useful.
Suggestion plz . Thanks.

Most Rails tests don't need stubs or mocks, but in this context, an example where you might need it is to mock a model in a controller or integration test.
Since controllers typically manipulate models, you will sometimes want to verify the model has been called in a certain way. You can usually do this just by asserting against the model's state, after the controller has been invoked, but occasionally you may wish to verify the actual call made from controller to model. In this case, you "mock" the model using a Ruby mocking library and setup the expectation prior to calling the controller. The test will fail if the expected model method wasn't called.
Another motivation may be to fake some data being returned, in which case you would "stub" the model. Stubbing is just mocking without any kind of assertion, you can prepare some fake behaviour.
More info on Rails stubbing and mocking

Related

Jooq mock fetchInto

As i found it is possible to mock result of jooq request . But is it possible to mock fetchInto function for example?
I have this code
val addressSaved = dsl.selectFrom(address)
.where(address.CITY.eq(city))
.fetchOneInto(Address::class.java)
And I want to mock just fetchOneInto. It will make testing more easily I think.
How to mock xyzInto(Class<E>) methods
You can replace the implementation of all the xyzInto(Class<E>) style methods using a single SPI: The RecordMapperProvider as documented here:
https://www.jooq.org/doc/latest/manual/sql-execution/fetching/pojos-with-recordmapper-provider/
That way, irrespective of your specific query, you can always populate custom implementations of your Address class (or even some other subclass). You'll still need to mock the statement itself, though. Probably again using a MockConnection as you already discovered.
Mocking vs integration testing
You've probably made an informed decision regarding mocking vs. integration testing already, but for future visitors of this question, I'm still mentioning this:
In general, it is a lot easier and more useful to just integration test your code with your actual database (e.g. using testcontainers), and if you must mock things to test higher level logic, then mock your services, not jOOQ SQL statements.

How can I ise Page objects

I'm beginner in cucumber jvm, can anyone explain to me how can I work with page objects?
I don't know how can I organize my project.
A page object is an abstraction that simplifies the interaction with a web page when writing a test for the web page. It is one way to separate concern.
When you are implementing steps using Cucumber, you usually create a helper class that the step implementation delegates to. This helper class can, and often is, a page object.

Create a single, custom, globally available object in a rails app

I am having a very difficult time finding the answer to this. I want to create a custom class (this I know how to do) and have it get instantiated--one instance--that is globally accessible from within my application. I am looking to centralize and abstract some code and use this globally-available object as an interface. I can't believe how weird this is to figure out.
I need to have models, etc., available from within this object.
Help is appreciated.
I am running Rails 3.2.8.
Any model that you put in app/models will be autoloaded by Rails, so you can stick a custom model there.
The class will be available throughout your app, so whether you can just use class methods or not is up to you. If you want it to be a singleton, see this helpful article.
Lastly, if you need the model to instantiate in some specific way, just put it in an initializer. Any file in config/initializers will be run once as the app boots up.
You probably want a Singleton...
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/singleton/rdoc/Singleton.html
However, that will only be available to that apps process. If you run multiple app servers (ie. multiple thin instances or Passenger) each will have it's own instance.
If you need something truly global you'll have to look into other options.

Can we load multiple factories into the database in one shot?

Just started using factory girl. If one has to save a factory into the db then one has to run
FactoryGirl.create().
But is there any way to load a collection of factories into the database without having to call create on each of the factories?
If its of any help i'm using Ruby 1.9.3, Rails 3.2.8 and Factory Girl 4.1.
If you need a bunch of factories of different type, you'll simply have to create them individually. You can make this a bit less verbose by adding this to your test_helper.rb:
include FactoryGirl::Syntax::Methods
Then you can create factories like this:
create(:factory_name)
And of course, if you need a bunch of records of the same type, you can create them like this:
5.times { create(:factory_name) }
As mentioned in my comment, creating all your factories in one fell swoop on initialization of your test framework is counter-productive. The idea behind FactoryGirl is to provide just the data you need for each test case or context. This avoids dependencies between tests that tend to slip into a fixture-driven approach.

What is Object Mocking and when do I need it?

Many people use Mock Objects when they are writing unit tests. What is a Mock Object? Why would I ever need one? Do I need a Mock Object Framework?
Object Mocking is used to keep dependencies out of your unit test.
Sometimes you'll have a test like "SelectPerson" which will select a person from the database and return a Person object.
To do this, you would normally need a dependency on the database, however with object mocking you can simulate the interaction with the database with a mock framework, so it might return a dataset which looks like one returned from the database and you can then test your code to ensure that it handles translating a dataset to a person object, rather than using it to test that a connection to the database exists.
Several people have already answered the 'what', but here are a couple of quick 'whys' that I can think of:
Performance
Because unit tests should be fast, testing a component that
interacts with a network, a database, or other time-intensive
resource does not need to pay the penalty if it's done using mock
objects. The savings add up quickly.
Collaboration
If you are writing a nicely encapsulated piece of
code that needs to interact with someone else's code (that hasn't
been written yet, or is in being developed in parallel - a common
scenario), you can exercise your code with mock objects once an
interface has been agreed upon. Otherwise your code may not begin to
be tested until the other component is finished.
A mock object lets you test against just what you are writing, and abstract details such as accessing a resource (disk, a network service, etc). The mock then lets you pretend to be that external resource, or class or whatever.
You don't really need a mock object framework, just extend the class of the functionality you don't want to worry about in your test and make sure the class you are testing can use your mock instead of the real thing (pass it in via a constructor or setter or something.
Practice will show when mocks are helpful and when they aren't.
EDIT: Mocking resources is especially important so you don't have to rely on them to exist during the test, and you can mock the details of how they exist and what they respond (such as simulating a FileNotFoundException, or a webservice that is missing, or various possible return values of a webservice)... all without the slow access times involved (mocking will prove MUCH faster than accessing such resources in the test).
Do I need a Mock Object Framework?
Certainly not. Sometimes, writing mocks by hand can be quite tedious. But for simple things, it's not bad at all. Applying the principle of Last Responsible Moment to mocking frameworks, you should only switch from hand-written mocks to a framework when you've proven to yourself that hand-writing mocks is more trouble than it's worth.
If you're just getting starting with mocking, jumping straight into a framework is going to at least double your learning curve (can you double a curve?). Mocking frameworks will make much more sense when you've spent a few projects writing mocks by hand.
Object Mocking is a way to create a "virtual" or mocked object from an interface, abstract class, or class with virtual methods. It allows you to sort of wrap one of these in your own definition for testing purposes. It is useful for making an object that is relied on for a certain code block your are testing.
A popular one that I like to use is called Moq, but there are many others like RhinoMock and numerous ones that I don't know about.
It allows you to test how one part of your project interacts with the rest, without building the entire thing and potentially missing a vital part.
EDIT: Great example from wikipedia: It allows you to test out code beforehand, like a car designer uses a crash test dummy to test the behavior of a car during an accident.
Another use is it will let you test against other parts of your system that aren't built yet. For example, if your class depends on some other class that is part of a feature that someone else is working on, you can just ask for a mostly complete interface, program to the interface and just mock the details as you expect them to work. Then, make sure your assumptions about the interface were correct (either while you are developing, or once the feature is complete).
Whether or not you a mocking framework is useful depends in part on the language of the code you're writing. With a static language, you need to put in extra effort in order to trick the compiler into accepting your mock objects as a replacement for the real thing. In a dynamically-typed language such as Python, Ruby or Javascript, you can generally just attach the methods onto arbitrary object or class and pass that as the parameter -- so a framework would add much less value.
2 recommended mocking frameworks for .net Unit testing are Typemock Isolator and Rhino Mock.
In the following link you can see an explanation from Typemock as to why you need a mocking framework for Unit Testing.