My MacBook Pro with 8 GB 1067 MHz DDR3 RAM and 3.06 GHz Intel Core 2 Duo was running the fan continuously for couple of weeks. To fix it, I ran:
$ top
in the terminal. I found two ruby processes had been running for 160 hours continuously and were taking up 93% of the CPU usage. I killed them by doing:
$ kill -9 [process-id]
As soon as those two stray processes were killed, laptop became quiet again.
Wednesday, August 22, 2012
How to install tmux 1.6 on Mac OS
I was having difficulty installing the version 1.6, the older 1.4 version was being picked up. The fix:
1. /opt/bin should be in the path. You can append this to your path by editing the ~/.profile file. Mine looks like this:
##
# Your previous /Users/bparanj/.profile file was backed up as /Users/bparanj/.profile.macports-saved_2010-06-07_at_22:52:52
##
# MacPorts Installer addition on 2010-06-07_at_22:52:52: adding an appropriate PATH variable for use with MacPorts.
export PATH=/opt/local/bin:/opt/local/sbin:/opt/bin:$PATH
# Finished adapting your PATH environment variable for use with MacPorts.
export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"
2. curl -OL http://downloads.sourceforge.net/project/levent/libevent/libevent-2.0/libevent-2.0.19-stable.tar.gz
3. tar xzf libevent-2.0.19-stable.tar.gz
4. cd libevent-2.0.19-stable
5. ./configure --prefix=/opt
6. make
7. sudo make install
8. tar xzf tmux-1.6
9. cd tmux-1.6
10. LDFLAGS="-L/opt/lib" CPPFLAGS="-I/opt/include" LIBS="-lresolv" ./configure --prefix=/opt
11. make && sudo make install
12 which tmux
showed that the older 1.4 version was being picked up from /opt/local/bin, I deleted it by : sudo rm /opt/local/bin/tmux
Saturday, August 11, 2012
Rails 3.2 Errno::EACCES Permission Denied when uploading files
1. Make sure the directory has the right permission:
chmod -R 777 uploads
2. The uploads directory is at the same level as app directory. You can change the upload location from the public folder to any folder by customizing the store_dir in your uploader class:
def store_dir
"#{Rails.root}/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
3. You also have to define cache_dir in your uploader class, otherwise it will still throw exception.
def cache_dir
"#{Rails.root}/tmp/uploads/cache/#{model.id}"
end
chmod -R 777 uploads
2. The uploads directory is at the same level as app directory. You can change the upload location from the public folder to any folder by customizing the store_dir in your uploader class:
def store_dir
"#{Rails.root}/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
3. You also have to define cache_dir in your uploader class, otherwise it will still throw exception.
def cache_dir
"#{Rails.root}/tmp/uploads/cache/#{model.id}"
end
Monday, July 16, 2012
Error: This transaction cannot be processed due to an invalid merchant configuration.
ActiveMerchant 1.26, Rails 3.2
Resolution:
1. Create your selling test account using the Preconfigured option.
2. Under Account Type, select Website Payments Pro.
3. My Account --> Profile --> API access to get API username, API Password and Signature
Resolution:
1. Create your selling test account using the Preconfigured option.
2. Under Account Type, select Website Payments Pro.
3. My Account --> Profile --> API access to get API username, API Password and Signature
Remember the API credentials are different from the test login account. You have to save the login password to the Sandbox account in Step 1 above. There is no way to go back and view the login password to the Sandbox account.
Sunday, July 08, 2012
remove github prompt when checkin
Change the url that has https to :
url = git@github.com:your_github_username/your_project.git
url = git@github.com:your_github_username/your_project.git
Saturday, June 23, 2012
TDD Screencasts by Kent Beck
1. Test for remove operation does not fail. He writes a test and does not run it, he goes to the implementation and implements. Then he runs the test and it passes.
2. Interesting to see how he uses the debugger to learn about the API and uses that information to write a test.
2. Interesting to see how he uses the debugger to learn about the API and uses that information to write a test.
Friday, June 22, 2012
Skip Bundle Install and Test Unit When Creating Rails 3.2 project
rails new ipn --skip-bundle --skip-test-unit
Wednesday, June 06, 2012
github push is prompting for username and password
I was getting this error for https://github.com/bparanj/mongodb_specs repo. Fix :
$git config remote.origin.url git@github.com:bparanj/mongodb_specs.git
$git config remote.origin.url git@github.com:bparanj/mongodb_specs.git
Thursday, May 31, 2012
-bash: mongod: command not found
export PATH=$PATH:/usr/local/mongodb/bin
For Mongodb 2.0.3
mongod --dbpath /Users/bparanj/data/mongodb
The dbpath is the path to the mongodb.config file
which contains :
dbpath=/Users/bparanj/data/mongodb
Deploying to a VPS
To get the http://railscasts.com/episodes/335-deploying-to-a-vps?view=asciicast working I had to do :
1. apt-get install sqlite3 libsqlite3-dev
2. Add : gem 'pg' and gem 'unicorn' to Gemfile
1. apt-get install sqlite3 libsqlite3-dev
2. Add : gem 'pg' and gem 'unicorn' to Gemfile
Wednesday, May 30, 2012
undefined local variable or method `autotest' for main:Object
This error happens when you have this : require autotest/fsevent
in your ~/.autotest file, change it to : require 'autotest/fsevent'
Thursday, May 10, 2012
Data Driven Unit Test
How do you avoid loops in your specs?
Like Alex points out, this is a test smell according to Gerard Mezos. In .NET they have something called as data driven unit test. In Ruby we can accomplish the same thing using the following:def data_driven_spec(container)
container.each do |element|
yield(element)
end
end
and in your test you can do :
it "should return back slash pre-pended to all special characters" do
SPECIAL_CHARACTERS = ["?", "^", "$", "/", "\\", "[", "]", "{", "}", "(", ")", "+", "*", "." ]
data_driven_spec(SPECIAL_CHARACTERS) do |special_character|
result = Regexpgen::Component.match_this_character(special_character)
result.should == "\\#{special_character}"
end
end
The code is taken from my regexpgen ruby gem. My test differs from the message that goes in to the it method. I have raised the level of abstraction, whereas Alex substitues the a variable to vary the message.
Wednesday, May 09, 2012
Creating a Ruby gem with RSpec as the test framework
1. bundle gem 'your-gem-name'
2. Run : rspec --init from your gem directory to generate the spec/spec_helper.rb and .rspec files.
.rspec has the configuration such as color and format of the output when specs are run.
2. Run : rspec --init from your gem directory to generate the spec/spec_helper.rb and .rspec files.
.rspec has the configuration such as color and format of the output when specs are run.
Tuesday, May 01, 2012
irb tricks
1. touch ~/.irbrc
2. Edit the .irbrc and add the following code:
require 'pp'
require 'rubygems'
class Object
def ls
%x{ls}.split("\n")
end
def pwd
Dir.pwd
end
def cd(dir)
Dir.chdir(dir)
pwd
end
end
alias p pp
3. Now whenever you open an irb session you can now list the directory contents by doing ls, print working directory by pwd and change directory by doing cd "directory-name".
2. Edit the .irbrc and add the following code:
require 'pp'
require 'rubygems'
class Object
def ls
%x{ls}.split("\n")
end
def pwd
Dir.pwd
end
def cd(dir)
Dir.chdir(dir)
pwd
end
end
alias p pp
3. Now whenever you open an irb session you can now list the directory contents by doing ls, print working directory by pwd and change directory by doing cd "directory-name".
Friday, April 27, 2012
Solution for Ruby Koans
You can download by solution from here https://github.com/bparanj/ruby-koans-edgecase.
This took me 5.5 hours to complete. I broke this down into 11, 30 minutes sessions over a period of two weeks.
Things that I learned:
1. It was a "aha" moment when I worked through a series of tests that described the behavior of a class. You have to do the exercises to get the feel for describing the behavior or specification of a class.
2. It helps you to find your strengths and weakness so you will know where to focus your learning efforts.
This took me 5.5 hours to complete. I broke this down into 11, 30 minutes sessions over a period of two weeks.
Things that I learned:
1. It was a "aha" moment when I worked through a series of tests that described the behavior of a class. You have to do the exercises to get the feel for describing the behavior or specification of a class.
2. It helps you to find your strengths and weakness so you will know where to focus your learning efforts.
How to install rubygems from source on Ubuntu 10.04
1. wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz
2. Extract : tar xvzf rubygems-1.3.6.tgz
3. cd to rubygems directory and run : ruby setup.rb
4. sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
Check version by either : gem -v or gem env
2. Extract : tar xvzf rubygems-1.3.6.tgz
3. cd to rubygems directory and run : ruby setup.rb
4. sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
Check version by either : gem -v or gem env
`merge': can't convert String into Hash
This error happens when you have syntax error in your .gemrc file. Fix it. gem env will work again.
How to install Ruby 1.8.7 on Ubuntu 10.04
sudo aptitude install ruby1.8-dev ruby1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl
sudo ln -s /usr/bin/irb1.8 /usr/bin/irb
sudo ln -s /usr/bin/ruby1.8 /usr/bin/ruby
Check the Ruby version :
ruby -v
undefined method `name' for RubyToken::TkLPAREN
I got that error message when I installed httpclient on Ubuntu 10.04. The gem got installed the error is due to the rdoc. You can turn off the installation of rdoc by appending no rdoc switch to the .gemrc file :
echo 'gem: --no-ri --no-rdoc' >> ~/.gemrc
The above command will append the 'gem: --no-ri --no-rdoc' to your .gemrc file.
echo 'gem: --no-ri --no-rdoc' >> ~/.gemrc
The above command will append the 'gem: --no-ri --no-rdoc' to your .gemrc file.
How to append to a file in Ruby
my_file = File.open('file_name', 'a')
Once you open the file in append mode, you can write to it. It will get appended to existing contents of the file.
How to list all files with a given extension in Ruby
Dir["*.xml"].each do {|f| p f}
Dir will return all xml files as an array. The block prints the name of the xml file.
Dir will return all xml files as an array. The block prints the name of the xml file.
How to list all files in a directory in Ruby
Dir.foreach(".") do {|f| p f}
This will print all the file names in the current directory including files that begin with a period.
This will print all the file names in the current directory including files that begin with a period.
How to copy local file to a remote Ubuntu server
scp -i ./your-key.ssh foo.rb user-name@101.101.101.101:.
Where your-key.ssh and foo.rb are in the directory where you are running scp. Since you have . after : at the end of ip address, the local file foo.rb will get copied to the root directory of your remote machine.
Where your-key.ssh and foo.rb are in the directory where you are running scp. Since you have . after : at the end of ip address, the local file foo.rb will get copied to the root directory of your remote machine.
How to compare Time in RSpec
When you are dealing with Time the == operator will not pass the test when you compare the time objects. Quick fix is to call to_s and use == to compare the time string values. Like this:
my_timestamp.to_s.should eq("Mon Apr 09 20:56:25 UTC 2012")
Reference:
Comparing time in rspec
Monday, April 23, 2012
no such file to load -- zlib
1. Go to the directory where you extracted the Ruby package:
Ex : cd ~/temp/ruby-1.8.7-p248/ext/zlib
2. ruby extconf.rb
3. sudo make && sudo make install
Ex : cd ~/temp/ruby-1.8.7-p248/ext/zlib
2. ruby extconf.rb
3. sudo make && sudo make install
Tuesday, April 17, 2012
How to limit the number of records returned by mysqldump
How to restrict the size of mysqldump?
mysqldump --where="true LIMIT 1000" -u user-name -p db-name > exported-data.sql
mysqldump --where="true LIMIT 1000" -u user-name -p db-name > exported-data.sql
How to list all the loaded gems on a server
Open a Rails console and type:
$:.each do |x|
p x
end;
p "hi"
$:.each do |x|
p x
end;
p "hi"
$: variable contains the list of all gems loaded into the system. I am suppressing the output of array of those gems by doing ; p "hi" after the end.
Monday, April 16, 2012
How to convert ppk file to normal ssh key in Ubuntu 10.04
sudo apt-get install putty-tools
puttygen your_file.ppk -O private-openssh -o new_file_name
puttygen your_file.ppk -O private-openssh -o new_file_name
scp permission denied publickey
How to copy a file from a remote Ubuntu server to your machine using scp and private key
scp -i /path/to/your_private_key_file user@your_host_or_ip:/path/on/the/remote/machine/file_name .
This will copy file_name to current directory in your local machine
scp -i /path/to/your_private_key_file user@your_host_or_ip:/path/on/the/remote/machine/file_name .
This will copy file_name to current directory in your local machine
How to install mysql gem on Ubuntu 10.04
sudo apt-get install mysql-server mysql-client sudo apt-get install libmysql-ruby libmysqlclient-dev sudo gem install mysql
Install mysql database connector by running the above commands.
How to install Nokogiri on Ubuntu
libxml2 is missing error message is due to missing libraries. Install the pre-requisite library with:
sudo apt-get install libxslt-dev libxml2-dev
How to install curb gem on Ubuntu 10.04
sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev
How to install bson_ext on Ubuntu 10.04
Using Bundler 1.1.3 for some reason does not work. Solution:
sudo gem install bson_ext -v=1.0.1
installs the gem.
sudo gem install bson_ext -v=1.0.1
installs the gem.
How to ssh using a given private key
ssh -i /path/to/your_private_key_file user-name@your-ip-address-here
Friday, April 13, 2012
It is recommended that your private key files are NOT accessible by others
I was getting this error : Permissions 0644 for '/home/bparanj/Downloads/my-file.ssh' are too open. when I was ssh ing into a box.
Solution:
sudo chmod 600 your-private-key.ssh
Monday, April 09, 2012
Rails Recipes 3rd Edition
The recipe: Focus Your Tests with Mocking and Stubbing show how to use stubs and mocks. It violates one of the testing best practices. DO NOT mock external services. Why? Because you cannot drive the design of a third party library. For a good discussion on this topic read the "Growing Object Oriented Software Guided by Tests".
I scanned through the book, I was a bit disappointed. Lot of the recipes are just from the old book.
I scanned through the book, I was a bit disappointed. Lot of the recipes are just from the old book.
Saturday, March 17, 2012
WARNING: 'require 'rake/rdoctask'' is deprecated. Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead. WARNING: 'require 'rake/rdoctask'' is deprecated. Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead
Include rdoc in the Gemfile :
group :development, :test do
gem 'rcov'
gem "rdoc", '~> 3.12'
end
Run bundle install.
group :development, :test do
gem 'rcov'
gem "rdoc", '~> 3.12'
end
Run bundle install.
Tuesday, March 13, 2012
Using Stubs with Test Spy in Ruby
While I was working on my super stealth product of my company - Affiliate Tracking system, I came across a problem during testing. I had to test the cookie setting logic of my controllers. It was straightforward to test that the cookie was set for the happy path. For the alternative scenario it became tricky to test because RSpec and Rails framework did not play that well together. I even read Devise Rails plugin code to see how Jose Valim handled cookie related problems during testing. No luck. One solution I found was on Stackoverflow. How do I test cookie expiry?
This technique is a great example of Test Spy described in Gerard Mezos book xUnit Test Patterns. Basically, you install a spy and check the results collected by the test spy in the verification phase. In this case the Hash is the Test Spy that collects data. See how the stub is used to install the spy in the SUT? It overcomes the problems and isolates the SUT from the Rails framework and allows the code to be tested easily.
In my TDD bootcamps, the topic on Stubs and Mocks generates lot of discussion. To clear confusion that surrounds the stubs and mocks, I would state : Read Martin Fowler's paper on Mocks Aren't Stubs, Stub can never fail your test, only mocks can fail your test. Using stubs in combination with a spy like this makes stubs seem like they can in fact fail your test. But only the data collected by the Test Spy decides whether the test passes or not. So the stub's main purpose is to just isolate the production code from Rails framework and allow access to the internal state of the SUT where there is no direct way to access it.
# app/controllers/widget_controller.rb
...
def index
cookies[:expiring_cookie] = { :value => 'All that we see or seem...',
:expires => 1.hour.from_now }
end
...
# spec/controllers/widget_controller_spec.rb
...
it "sets the cookie" do
get :index
response.cookies['expiring_cookie'].should eq('All that we see or seem...')
# is but a dream within a dream.
# - Edgar Allan Poe
end
it "sets the cookie expiration" do
stub_cookie_jar = HashWithIndifferentAccess.new
controller.stub(:cookies) { stub_cookie_jar }
get :index
expiring_cookie = stub_cookie_jar['expiring_cookie']
expiring_cookie[:expires].to_i.should be_within(1).of(1.hour.from_now.to_i)
endThis technique is a great example of Test Spy described in Gerard Mezos book xUnit Test Patterns. Basically, you install a spy and check the results collected by the test spy in the verification phase. In this case the Hash is the Test Spy that collects data. See how the stub is used to install the spy in the SUT? It overcomes the problems and isolates the SUT from the Rails framework and allows the code to be tested easily.
In my TDD bootcamps, the topic on Stubs and Mocks generates lot of discussion. To clear confusion that surrounds the stubs and mocks, I would state : Read Martin Fowler's paper on Mocks Aren't Stubs, Stub can never fail your test, only mocks can fail your test. Using stubs in combination with a spy like this makes stubs seem like they can in fact fail your test. But only the data collected by the Test Spy decides whether the test passes or not. So the stub's main purpose is to just isolate the production code from Rails framework and allow access to the internal state of the SUT where there is no direct way to access it.
Saturday, March 10, 2012
TDD Bootcamp Videos
You can watch the TDD Bootcamp videos on YouTube. It is over 5.5 hours of recording.
Tuesday, February 07, 2012
Testing and Command Query Separation Principle
The term 'command query separation' was coined by Bertrand Meyer in his book "Object Oriented Software Construction".
The fundamental idea is that we should divide an object's methods into two categories:
Queries: Return a result and do not change the observable state of the system (are free of side effects).
Commands: Change the state of a system but do not return a value.
Because the term 'command' is widely used in other contexts it is referred as 'modifiers' and 'mutators'.
It's useful if you can clearly separate methods that change state from those that don't. This is because you can use queries in many situations with much more confidence, changing their order. You have to be careful with modifiers.
The return type is the give-away for the difference. It's a good convention because most of the time it works well. Consider iterating through a collection in Java: the next method both gives the next item in the collection and advances the iterator. It's preferable to separate advance and current methods.
There are exceptions. Popping a stack is a good example of a modifier that modifies state. Meyer correctly says that you can avoid having this method, but it is a useful idiom. Follow this principle when you can.
From jMock home page: Tests are kept flexible when we follow this rule of thumb: Stub queries and expect commands, where a query is a method with no side effects that does nothing but query the state of an object and a command is a method with side effects that may, or may not, return a result. Of course, this rule does not hold all the time, but it's a useful starting point.
The fundamental idea is that we should divide an object's methods into two categories:
Queries: Return a result and do not change the observable state of the system (are free of side effects).
Commands: Change the state of a system but do not return a value.
Because the term 'command' is widely used in other contexts it is referred as 'modifiers' and 'mutators'.
It's useful if you can clearly separate methods that change state from those that don't. This is because you can use queries in many situations with much more confidence, changing their order. You have to be careful with modifiers.
The return type is the give-away for the difference. It's a good convention because most of the time it works well. Consider iterating through a collection in Java: the next method both gives the next item in the collection and advances the iterator. It's preferable to separate advance and current methods.
There are exceptions. Popping a stack is a good example of a modifier that modifies state. Meyer correctly says that you can avoid having this method, but it is a useful idiom. Follow this principle when you can.
From jMock home page: Tests are kept flexible when we follow this rule of thumb: Stub queries and expect commands, where a query is a method with no side effects that does nothing but query the state of an object and a command is a method with side effects that may, or may not, return a result. Of course, this rule does not hold all the time, but it's a useful starting point.
Saturday, February 04, 2012
Stubs are not Mocks - Concise Version of Martin Fowler's Article
Stubs - a common helper to testing environments. There is a difference in how test results are verified: a distinction between state verification and behavior verification. Focusing on one element of the software at a time -hence the common term unit testing. The problem is that to make a single unit work, you often need other units.
- Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
- Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
- Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
- Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
Only mocks insist upon behavior verification. The other doubles can, and usually do, use state verification.
The classical TDD style is to use real objects if possible and a double if it's awkward to use the real thing. A mockist TDD practitioner, however, will always use a mock for any object with interesting behavior.
An acknowledged issue with state-based verification is that it can lead to creating query methods only to support verification. It's never comfortable to add methods to the API of an object purely for testing, using behavior verification avoids that problem.
Subscribe to:
Posts (Atom)