The best friends for rspec

 
Testing is a concept very easy to grasp but it can be sometimes difficult to apply to a project. Rails is particularly friendly with this though, in the sense that it introduces you to the concept of testing from the very beginning, even so that every time you use a generator, it usually generates the proper testing files.
 
There are different kinds of testing mechanism, but here I want to talk about unit testing. The formula that I've used which BTW is not a great secret perse, is a combination of (rspec + faker + factory_girl), they are very specific is really easy to understand them all very quickly.
 
Rspec – Is the basic for unit testing, it uses a domain specific language (DSL) to describe the uses cases.
Factory_girl – is a great object generator, if you want something to replace fixtures factory_girl would be at the top of the list.
Faker – Do not overthink strings types, URLS, name, addresses, emails, username, etc. Better use this gem to provide random values for the testing.
 
So this are the gems that will do the work:
  •  rspec-rails
  •  factory_girl_rails
  •  faker
 
The setup for all of them is pretty straightforward I would say that you should start adding and setting them up one at a time in that order. This is a scenario for testing a controller API,
 
it "should not allow to create branch without company" do
      post :create, branch_without_company
      expect(response).to have_http_status(:bad_request)
      expect(json_response[:error]).to be_eql("Please provide a valid company_id")
end
 
There you go 3 lines long for a use case of the wrong request, if you are wondering what is branch_without_company is an object created by factory girl that basically do not have any company link to it.
 
let(:branch_without_company) {attributes_for(:branch,company:nil)}
 
 

Facebook icon Twitter icon LinkedIn icon e-mail icon