Recently, while testing with rspec, I find some of my test cases are failing.On close look I find that,these are the tests related to action which make some API call. Since, the client is not ready with there API, I have mocked the API functionality myself and runing at port 3030.
So, obviously since the server is not getting started at 3030 automatically, the test is failing. On starting the server at port 3030 manually , the test passes. So, The problem is to start the server at 3030.
To start it automatically whenever rspec is run
-> create a file(I called it start_servers.rb) in spec/support folder. all the files within this folder is executed whenever rspec is run. So, whatever intialization you want to do for rspec, you should add to a file in this folder
-> Add below, lines of code to it
#Handling thin server for mocked data
mock_server_path = File.join(Rails.root, “tmp”, “pids”, “thin.pid”)
thin_pid = File.read(mock_server_path).to_i
puts “thin server already running on 3030…”
puts “starting thin server at 3030 for mocked API…”
system “thin start -p 3030 -d”
whenever, we start rails server it create server.pid file in tmp/pid folder, for thin server it will create thin.pid, simelerly mongrel.pid when rails start with mongrel server. So, basically, we are retriving the pid form these file(thin.pid in my case) and checking if the process running for that or not in the begin block…IF it is not running Process.getpgid thin_pid will throw exception Errno::ESRCH, and control passes to rescue block where we will start the server. If we just want to handle the Errno::ESRCH we can definie begin rescue block as below also.
Since, Iam not doing anything with that exception, I avoided it, infact I want to start the server for any type of exception in the begin block, say when the file thin.pid is not at all present and so on
Now, whenever I run rspec, the thin server will automatically start at port 3030. You can see in the log as below
arun@arun-yadav:~/Projects/third-pillar$ rspec #running rspec on terminal
starting thin server at 3030 for mocked API…