Monday, August 12, 2013

Writing tests: RSpec's reason for Lambda

Most of my tests have been using the standard test format:

it "should add the thing to the db" do
  post :message, :content => "yadda yadda", :id => @user.user_id
  response.should change(Message, count).by(1)
end

However I'm now learning about Lambda's, which there have been some great posts recently about (i.e. Blocks v Procs v Lambdas). Lambda's themselves are a mathematical convention for improving readability of a formula. In the case of RSpec, Lambda's allow me to test the function, and not the response, for a change in my database.

My previous example actually says that the response would be the reason that the count changed. But if I have an empty db, or want to display data in my db temporarily to demonstrate that the function is correct, I can use a Lambda to my benefit. It essentially wraps my code in the before/after, so I can just do the following:

it "should add the thing to the db" do
  lambda do
    post :message, :content => "yadda yadda", :id => @user.user_id
  end.should change(Message, count).by(1)
end

Overall, the 2nd version is checking that I created a Message based on the action inside the Lambda, versus the 1st version is looking at the response to change the action.

No comments:

Post a Comment