How to stub in RSpec 3 [RAILS, TDD]?


Recently, I have been doing whole bunch of spec rewriting from RSpec 2 to Rspec 3. As a result I have found that documentation is not that straightforward, and some cases you need to really spend time and figure out yourself. So I’ll be posting some cases that I have not been able to find in docs, just as notes for myself, and hopefully it will be useful for someone else.


Use Case:

I have JSON file that I need to read, and I already have tests that this JSON file opens properly.  I also have a Validator that looks for certain patterns keys in this JSON file. Validator leaves separately from the main app, and I don’t want to replicate File Upload -> File Save to Cloud -> File Open in my Validator Tests, I just want on every to return certain data, and it does not matter to me what exactly is being read, and if path exists or not.

How would I do it in Rspec ?

data = {:name => "test" , :description => "test"}.to_json
allow(File).to receive(:read).and_return(data)

What does it give you ?

It looks for every in the scope of your spec and instead of actually reading file returns ‘data‘ every time.

Cool, huh ?



Posted in Programming Languages, Rails, Rspec | Tagged , , , , , | Leave a comment

How to stub an IP in Ruby on Rails, RSpec Version 3 ?

Often when you are writing unit tests, you want to mock your IP address. Some of the uses cases could be – you are checking if IP is within the certain range.

For RSpec 2.x  mocking  IP would look like this:


Taken from here

However, if you try to do it in RSpec 3.x, it will give you an error since ‘any_instance‘ syntax is deprecated.

To make the same work for RSpec 3.x use this:

   allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("")

Posted in Programming Languages | Tagged , , , , , , | Leave a comment

How to scaffold JavaScript Web Application in seconds using YEOMAN ? (example with Backbone Marionette)

Hey guys,

Today I want to discuss an issue that I have been recently facing, and how to solve it.

The issue is:

How to set up a new JavaScript web app as quickly as possible and start developing, instead of worrying about dependencies and digging into configuration files trying to tie different libraries together ?

If you are a Rails developer, you will understand what I mean. In Rails you can scaffold your application and have a mockup that you can start building on in seconds. I haven’t been able to find such tool for JavaScript web apps… Until now…..

My colleague Tim showed me a tool today, that does the job for you.

The tool is called: YEOMAN .

YEOMAN uses 2 other tools for JavaScript that should be in a must-have list for any JavaScript Web Developer.

They are:

a. Grunt  – JavaScript task runner
b. Bower –  A package Manager for Web

The good thing is that to develop simple Web App with YEOMAN, you don’t even need to know how to use those tools, because YEOMAN does everything for you. However, I highly encourage you to read documentation for both tools, because they will make your JavaScript development SO MUCH EASIER!

Finally, after this long intro, let’s get to setting up our first JavaScript Backbone Marionette application using YEOMAN.

Before you start:

You need to have: Node.JS and NPM. To be honest, if you are planning to develop web apps – you will need them anyway.

You can find how to install Node.JS and NPM here .

When you have Node and NPM in place, you need to:

1. Install Bower and Grunt.  using NPM:

npm install -g grunt-cli
npm install -g bower

Tip: ‘-g’ in npm install makes element that you have installed  – global, so you just need to install it once, and use it  for multiple applications.

2. Install YEOMAN

npm -g install yo

3. Install YEOMAN generator for Marionette.JS

npm install -g generator-marionette

4. Install Mocha Generator that Marionette Generator uses:

npm install -g generator-mocha-amd

5. Create Web App Folder, Scaffold Marionette Application using YEOMAN Generator:

mkdir WebAppTest
cd WebAppTest
yo marionette

Expected output: (If you need any components I said no to, please put Y instead of ‘n’:

 | |
 |--(o)--| .--------------------------.
 `---------´ | Welcome to Yeoman, |
 ( _´U`_ ) | ladies and gentlemen! |
 /___A___\ '__________________________'
 | ~ |
 ´ ` |° ´ Y `
Out of the box I include HTML5 Boilerplate, jQuery, Backbone.js, Marionette, Handlebars, Require and Modernizr.
 [?] Would you like to install the full express app or simply the marionette generators? Yes
 [?] Would you like to include MongoDB for storage? No
 [?] Would you like to include Socket IO for real time communication? No
 [?] Would you like to include Baucis for REST? No
 [?] Where do you want the Bower components installed? (bower_components) ENTER

Note: this will take a while,  but in the end YEOMAN will create a web app, put all necessary dependences and even tests. Isn’t it amazing ?

6. Run your application:


This will load your browser and you will be able to see this screen:

Screen shot 2014-02-24 at 12.40.06 PM

So here you have your scaffolded Marionette application that includes Handlebars.JS templates and Unit tests.

Of course it doesn’t stop on Marionette, there are plenty of generators for YEOMAN allowing you to scaffold many web apps of your choice.

That’s it for today,

Try it and let me know how it goes!


Posted in Backbone.JS, Handlebars.JS, JavaScript, Marionette.JS, open-source, Programming Languages | Tagged , , , , , , , | 6 Comments

RAILS, HAML : How to put Checkbox and label on the same line, with translations

Hey guys!

Today I have decided to share with you little secret, that can save you quite some time, while writing templates with HAML.

While creating a form for one of the projects, I needed to put a checkbox within the same line as label and also I had to make my label a “translation”.

I googled and the closest which I was able to find was:

However, It didn’t really solve my “translation” problem.

Initially my code looked like this:

= simple_form_line do
  = f.label t('.send_email')
  = f.check_box :send_email, class: "checkbox"

.send_email in this case is a translation from my eng.yml file which equals to “Send credentials to user by email”.

The code produced this output:


However, what I needed my checkbox and message to be on the same line. This is how I was able to solve it:

= simple_form_line do<
  %label.checkbox{ :for => "send_email" }
    = f.check_box :send_email, class: "checkbox"
    = t(".send_email")

(Sorry if wordpress screwed indentation!!!)

And here is how output looks like:


That’s it for today!

Have a wonderful day!



Posted in Programming Languages, Rails | Tagged , , , , , | Leave a comment

How to make a contact form with Bootstrap 3 ? (JQuery/PHP/HTML5/JqBootstrapValidation)

Hey guys!

Today we will talk about such essential feature for any website as contact form. Recently, while working on one of the projects, I had a pleasure combining couple of very nice tools (Bootstrap 3 + JQuery + jqBootstrapValidation), which resulted in minimalistic , but powerful contact form, that would be a good addition to any website.

Contact me form


In this post I will walk you through the process of developing this form. Also if you just want to put it in your website, just pulled from my github repo and have fun.

Sounds good ?

Let’s start.

When I was developing my form I had in mind following goals:

– Minimalistic design
– Track person’s contacts for future communication
– Send form information directly to my email
– Validate input – client side and server side
– Show success when form is sent, or provide alternative method if something went wrong

As you might see – nothing special. I would love if somebody else would provide me this solution yesterday, when I was working on my project – this could save me some time! 🙂

Let’s divide our workflow into sections:
– Required Libraries
– UI
– Client-side Validation, JQuery – PHP Interaction
– PHP (so called server side)

Required Libraries

We will require following libraries :
Botostrap 3
–  jqBootstrapValidation

So all you need to do is just download necessary files and put them in.

After getting Bootstrap and jqBootstrapValidation our website tree will look like this:

– –  css
– – – bootstrap.min.css
– – js
– – – bootstrap.min.js
– – – jqBootstrapValidation.js

Let’s move to the UI part.


For the UI we will use Bootstrap 3 and some attributes from jqBootstrapValidation.js . I won’t cover Bootstrap 3 components as it will take far too long, but if something is unclear, please shoot me an email and I will clarify that for you.

So in the root of our website we need to create file form.html .

Final version of /form.html will look like this:

Contact form for your site by Anatoly Spektor
  <!-- Bootstrap CSS -->
  	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen" />

<!-- Contacts --></pre>
<div id="contacts">
<div class="row"><!-- Alignment -->
<div class="col-sm-offset-3 col-sm-6">
      <!-- Form itself -->
<form class="well" id="contactForm" name="sentMessage" novalidate="">Contact me
       <!-- Full Name -->
<div class="control-group">
<div class="controls">
	    <input class="form-control" id="name" type="text" placeholder="Full Name" required="" data-validation-required-message="Please enter your name" />

        <!-- Email -->
<div class="control-group">
<div class="controls">
		<input class="form-control" id="email" type="email" placeholder="Email" required="" data-validation-required-message="Please enter your email" /></div>
        <!--Message -->
<div class="control-group">
<div class="controls"></div>
<div id="success"></div>
 <!-- For success/fail messages -->
 <button class="btn btn-primary pull-right" type="submit">Send</button>

 <!-- JS FILES -->

<script type="text/javascript" src=""></script><script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script type="text/javascript" src="./js/jqBootstrapValidation.js"></script><script type="text/javascript" src="./js/contact_me.js"></script>

Sorry for this formatting, it’s hard to put code into WP, please find formatted version of form.html here

If you are familiar with Bootstrap – this code is pretty straightforward.

There are couple of important things I would like to point out:

  1. Since we are using jqBootstrapValidation, we need to put novalidate attribute into our form tag, otherwise HTML5 validation will clip jqBootstrapValidation validation.
  2. To change color/style of your error messages just change “.help-block” CSS class
  3. data-validation-* classes are used to specify custom message when user does something incorrectly. You can find more about those here.
  4. jqBootstrapValidation library looks at input and textarea tags and automatically puts validation if needed. For example if there is a “required” attribute, it automatically will put error message if the field is empty.

That’s all I can think of, if you have additional questions, please send me an email, or ask me in the comments below the post.

Client-side Validation, JQuery – PHP Interaction

So now we have finished the design of our form. Next step is to activate jqBootstrapValidation library, pass users data to PHP, which will send an email and finally show something to the user.

Most of these is done in one tiny JQuery function.

Here it is (file js/contact_me.js):

  Jquery Validation using jqBootstrapValidation
   example is taken from jqBootstrapValidation docs
$(function() {

     preventSubmit: true,
     submitError: function($form, event, errors) {
      // something to have when submit produces an error ?
      // Not decided if I need it yet
     submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit haviour
       // get values from FORM
       var name = $("input#name").val();
       var email = $("input#email").val();
       var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
           // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
	   firstName = name.split(' ').slice(0, -1).join(' ');
                url: "./bin/contact_me.php",
            	type: "POST",
            	data: {name: name, email: email, message: message},
            	cache: false,
            	success: function() {
            	// Success message
<div class="alert alert-success">");
 $('#success > .alert-success').html("<button class="close" type="button" data-dismiss="alert">Ă—")
 .append( "</button>");
 $('#success > .alert-success')
 .append("<strong>Your message has been sent. </strong>");
 $('#success > .alert-success')

 		  //clear all fields
 	   error: function() {
 		// Fail message
<div class="alert alert-danger">");
 $('#success > .alert-danger').html("<button class="close" type="button" data-dismiss="alert">Ă—")
 .append( "</button>");
 $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly to <a href="'"></a> ? Sorry for the inconvenience!");
 $('#success > .alert-danger').append('</div>
 		//clear all fields
         filter: function() {
                   return $(this).is(":visible");

      $("a[data-toggle=\"tab\"]").click(function(e) {

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {

For the most part I have took the function from jqBootstrapValidation examples. However, there are couple of things particularly interesting to us.

jqBootstrapValidation allows to overwrite submit on success behaviour, which I am doing in this case. If user submits everything without errors – I do a POST request to the file bin/contat_me.php with name, email and message.

File contact_me.php, which we will code in the next section, sends me an email with everything that user filled in. Also, I check If I am able to connect to this file, in this case I send back “Message sent successfully” to the user, otherwise I give an error telling user to email me directly ( use cases: for example if mail server is down, if validation on server side failed, if permissions to php file are incorrect etc) .

There is not much to add, but if you have any questions regarding this function do not hesitate to ask.

PHP (so called server side)

Finally, we got to the last piece of this puzzle. I have a php file that does some validation on the data received from form and sends me an email.

Here is my PHP file ( bin/contact_me.php )

// check if fields passed are empty 

 if(empty($_POST['name'])   ||    
    empty($_POST['email'])  ||
       echo "No arguments Provided!"; 	return false;    
  $name = $_POST['name']; 
  $email_address = $_POST['email']; 
  $message = $_POST['message']; 	 

 // create email body and send it	 
 $to = ''; 
 // put your email 
 $email_subject = "Contact form submitted by:  $name"; $email_body = "You have received a new message. \n\n". 				  
                   " Here are the details:\n \nName: $name \n ". 				  
                   "Email: $email_address\n Message \n $message"; 
 $headers = "From:\n"; 
 $headers .= "Reply-To: $email_address";	 

 mail($to,$email_subject,$email_body,$headers); return true;			 

As you might see my PHP file is even more simple. Of course you can add extra validation on top of it. For my use case I am just checking if fields are not empty and if email has correct format. If everything is correct, I create an email and use PHP’s mail function to email it.

That’s it.

You can find all these files here.

I hope this function will be useful for you!





(Thanks a lot to Corey Russell  for resolving some of the occurring issues)

Q:  I see “Sorry <Name> it seems that my mail server is not responding… Could you please email me directly to….”

A:  1. Go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.
2. If you try it from your desktop it won’t work as it doesn’t have a php server/client installed.


Posted in Bootstrap, HTML5, JavaScript, Jquery, open-source, Programming Languages | Tagged , , , , , | 191 Comments

How to find if a number is power 2 ? (Bitwise and Iterative) [Python Script]

As I have promised, I continue answering your questions.

One of the readers of wrote me an email asking How to find if a number is power 2 ? He also asked me to write a bitwise solution as well as an iterative  solution using Python. There are many examples of these kind of questions in the Internet, but I thought it would be nice to put one up here too,  since person asks.

Ok, here we go !

So first solution  is the bitwise one .

In this solution we will be using legendary bitwise operator AND (&). This solution is based on the unique property of all power 2 numbers having only one bit set to one and all other bits to zero. So number-1 will remove this one bit making expression equal to zero, if the number is power of two. You will notice that there is special case – number != 0 . If you put 0 into expression below, you will see that despite 0 being not power of two, expression will return true. So to eliminate special case, I just made sure that number is not zero.

Here is the function itself :

# Bitwise version
def powTwoBit(number):
  return (number & (number-1) == 0) and (number != 0)

Second solution is easier to understand if you are not a big fan of bitwise operations, since it uses regular looping and is based on the property that any number that is power of two has –  divisible by two without a remainder. So in this solution I loop and divide number by 2 until number is not equal to 1. If one of these divisions shows me that division produced a remainder, I know that number is not power of two. I also take into account special case – number must be positive.

#Iterative version
def powTwoIter(number):
	while (number != 1 and number > 0):
			# can do return here as well
			isPowOfTwo = False
	return isPowOfTwo and (number > 0)

So here they are – 2 solutions of how to find if a number is power of 2 in Python. I have put this code into github repo together with Unit Tests. So feel free to use it.

Of course there are many other solutions. For example you can create an array of power 2 values, sorted from least to greatest (the range that corresponds to the problem you are trying to solve) and use a binary search to find if your number corresponds to one of those in the array.

 Choose whatever works for you!



Posted in open-source, Programming Languages, Python, Useful Functions | Tagged , , , , | 1 Comment

How to check if a number is ODD or Even ? [PHP function]

Hey guys!

Long time no seen! Today I had a pleasure of going over myprogrammingblog emails, where many users have asked me to show solutions to different problems. Sorry for not being able to respond earlier, as I had whole bunch of things going on.

From now on, at least for a month, I will be regularly (read as 1 time in 1-2 days) posting some code examples for the problems you have asked me to take a look at. By the way, if you have any interesting problems, which you would like to share with me, please email me at: .

Quick Update:

I have opened myprogrammingblog Git repo, where I will be posting code examples discussed in this blog.

Repo URL is :

Now, back to business.

One of the readers ( I am not posting names/nicknames since some people don’t like to be addressed publicly) asked me:

How to check if a number is ODD or Even ?

To solve this problem I will use nice operator, available in most popular programming languages (e.g C/C++/Python/Java/PHP/JavaScript…you name it…) called modulo (%) .

Modulo – finds the remainder of the division.  That’s exactly what we need!

We know that EVEN numbers are those that can be equally (read without a remainder) divided into two groups. By using modulo we can check if the number divided by two does not have a remainder, than it is an EVEN number, otherwise it is ODD.

Bored already ? Here is the code (since no specific language was required, I have used PHP):


 * Description:
*		This small function returns true if passed number
*                     is divisible by two, false if not.
* @author: Anatoly Spektor
function isEven($number) {
	$isEven = false;
	if (is_numeric ($number)) {
		if ( $number % 2 == 0) $isEven = true;
	return $isEven;


In case you need Unit Tests for this function, they are available in the repo.

Thank you for sending me your questions!



Posted in GitHub, open-source, PHP, Programming Languages, Useful Functions | Tagged , , , , , , , , | 5 Comments