Mocking Screw-Unit

written by trotter on August 8th, 2008 @ 07:35 AM

I’m big on tests. Unit testing helps me clarify my thinking on problems and ensure that my code works well. When writing tests, it’s essential to have a good mocking framework to separate the things you are testing from the things you are not. In Ruby, I like using flexmock for Test::Unit and rSpec’s built in mocking framework when using it. In Javascript though, screw-unit doesn’t really come with a way to mock by default. (As an aside, screw-unit totally rocks for testing js.)

Thankfully, my coworker Topper (who’s a kickass dev, btw), has been playing around with adding mocking to screw-unit. He’s got a fork on github, docs at the previous link, and a quick example blog post. Click through and check this shit out, cause it’s hot.

Floating Pain

written by trotter on July 7th, 2008 @ 01:19 PM

Topper mentioned a tweet he saw to me in which someone asked why (4.6 * 100).to_i #=> 459. Though this seems like a ruby bug, it’s really just one of the annoying things you hit with rounding errors and floats. At issue is that #to_i floors the float, instead of rounding it. Since the value may be approximated at 459.999999, the #to_i floors it to 459. To have things work like you’d expect, use #round when converting Float to Fixnum. See below for some code examples:

  4.6.to_i           # => 4
  4.6.round          # => 5
  (4.6 * 100).to_i   # => 459
  (4.6 * 100).round  # => 460

How I Got Started Programming

written by trotter on June 26th, 2008 @ 11:06 PM

Paul says I’ve got to do this, and I don’t want to let him down. Giles tagged him first, so you should probably read his too.

How old were you when you started programming?

In third grade (when I was 8) I started started taking super nerd math classes with other super nerds. As part of those classes, they had us programming a turtle to draw things on the screen. Logo) was totally awesome and had me hooked on the magic of programming.

How did you get started programming?

After Logo, my dad (he was a CTO at the time) bought me Visual Studio and a few books on Visual Basic. It was lots of “Teach Yourself X in X days”, and I ran through VB, C++, and a little Delphi. Naturally, those books didn’t teach me to actually be good, though I did figure out how to make a few small games that I could play.

My dad was a CTO at an investment bank, which is the kind of place that treats a CTO like crap. I didn’t want to be the guy that got shat on, so in high school I dropped programming and started learning businessy things. I even picked my college based on the strength of its business school. Once I showed up, I realized that I didn’t like anyone at the business school, that philosophy was fun, and that math/econ could make me money. I promptly switched my major.

After college, I went to work at a job that I ended up hating, quit it, took a few months to figure out my life, and realized that I really loved programming. Thankfully I got lucky and read a blog post that tipped me to the beta book of AWDWR, which taught me a lot about real programming. I consider that the start of me becomming a real programmer, and not just some kid that can code.

What was your first language?

Logo! Drawing with turtles rocks so hard. After that it was VB, which let me push Windows around and made me a little cash.

What was the first real program you wrote?

I wrote my first useful program while working as an intern at a financial services firm. The company was using Axys (really bad website alert!) for portfolio analysis and had a tedious process for reconciling their branches with the back office. I wrote a VB program that helped them to perform these reconciliations more quickly, which I hear they still use.

What languages have you used since you started programming?

Logo, VB, C, C++, Delphi, Ruby, Objective-C, Erlang, Scheme, Javascript, Java, and maybe something else. Of those, I’d feel comfortable working on a project using Ruby, Javascript, Objective-C, or Erlang. I’m skilled enough in some of the others, but have vowed to never use them again. I’ll let you guess which.

What was your first professional programming gig?

2005 at the Nathan Kline Institute for Mental Health. There was a PhD there who needed ImageJ to talk to his microscope over a serial port and to have a lot of old scripts from ObjectImage translated into ImageJ. It was a fun job that let me work at my own pace and play a lot with the art of programming.

If there is one thing you learned along the way that you would tell new developers, what would it be?

Surround yourself with great people, and never be the smartest guy in the room. If you’re lucky enough to work at a company with some great programmers, you’ll learn a whole lot that way. If your company is full of 9-5 coders, join a local developer group or start your own. Nyc.rb and Philly On Rails totally rock, so you could always move to New York or Philly and learn from some of the best.

What’s the most fun you’ve ever had programming?

Logo. I used to love making that little turtle draw all sorts of fun things on the screen. There was no real need to make the turtle do things, I was doing it just for the joy of it. I managed to recreate some of that feeling when working on spec-unit, which is really my only useful open source contribution to date. Unfortunately, it only has one release ever, and I haven’t messed with it in two years.

On Working Remotely

written by trotter on June 22nd, 2008 @ 06:23 PM

Being on my honeymoon in St. Barths has got me thinking a bit about working remotely. Don’t worry, I’m not working on this trip. I’m more trying to think if ways I could stay on this trip indefinitely, but still manage to make some cash.

I’m no stranger to remote work. As some of you may know, I live in Philly but continue to work for Motionbox in New York. I commute two days per week, and spend the rest working from home in Philly. Over the past year, I’ve started to catalog my likes and dislikes with this arrangement, and I’m going to list some of my dislikes here along with some possible ways to improve things. For now, we’ll just look at the first problem I’ve encountered:

You’re out of touch

If you’re distributed while the rest of the team is collocated, you will be out of the loop. When your boss is walking around the office and stopping at various desks, he won’t be stopping at yours. If you’re looking to be recognized for your accomplishments, this can be a major problem. It’s difficult to advance in the company if you’re not visible.

To combat this problem, I’ve found getting everyone on IM and IRC to be very helpful. If your company uses an open office, you’re in luck. The noise from the floor plan typically causes people to use headphones, so they’ll be much more prone to use IM and IRC for all their communication (even with those people right next to them). Another good technique is to send copious amounts of email. If people are cataloging what should be done and who has done what through email (a good practice regardless), then it’s much easier for you to keep track of what is happening in the office.

I don’t think that Skype or frequent phone calls help much in this regard. Typically, you’re only talking to one person and all the speaker phone arrangements I’ve seen aren’t that great. Voice is great for quickly hashing out the details of a plan with one other person, but is terrible as a mechanism for keeping up with the goings on of the company.

Making time (and spending the money) to get to the office at least once a month is invaluable. Though email, IM, and IRC help, they’re not a real substitute for quality time in person. One of the most important things I’ve done at Motionbox is to know when people are going out for after work drinks to celebrate various accomplishments and made sure that I was able to be in town for them. Though it sounds silly to talk about drinking as an important part of work, the main thing you miss by being remote is the social component. It’s much more important to get in town to socialize than it is to do actual work. You’ll have plenty of time to work when you’re home alone the next day.

Anyone have any thoughts on other ways to keep in touch while working remotely?

BelongsToDemeter

written by trotter on June 10th, 2008 @ 10:30 PM

While playing with Rails the other day, I thought it would be fun if you could get at attributes of a belongs_to association without having to do the whole traverse association and check for nil thing.


# Something like...
@person.group_name  # => "Pizza Fans!" || nil

# Instead of...
@person.group ? @person.group.name : nil # => "Pizza Fans!" || nil

Thinking this would be a fun chance to play with some meta, I threw together BelongsToDemeter, which you can find over on GitHub. It's a rails plugin, but don't expect it to actually install using script/plugin. The code is complete and utter crap, so it's probably best that Rails won't install it. It is slow, and most likely prone to error. Still, it's a fun little thought experiment, and I may decide to clean it up then speed it up if someone tells me they like it.

It does what I explained above and also lets you do fun things like this, which I think are useful when assigning associations through a form:


# Lookup the user 'Bob' by login and assign 
# it to the user association
@character.user               # => nil
@character.user_login = "bob"
@character.user.login         # => "bob"

Anyway, go over to GitHub and check out BelongsToDemeter. When you're done, let me know if you like the concept. After all that, go erase all memory of the implementation details from your mind, they're ugly.

Macro Tests

written by trotter on June 4th, 2008 @ 10:22 PM

I went to Josh Susser's talk at RailsConf last week, where he mentioned that no one really writes macro tests with rSpec. Naturally, I found this to be a true shame, since I think macro tests are a great way to clean up your code. What's a macro test you ask? Sit right there and I'll tell you.

A macro test is a test that defines other tests for you. It's a great way to reduce repetition in your test code, thereby making it easier to read. Take these three tests as an example:

describe 'GET /users/:user_id/posts/:post_id/comments' do
  it 'should be a success' do
    get :index, :user_id => 2, :post_id => 3
    response.should be_success
  end

  it 'should 404 without a user id' do
    get :index, :post_id => 3
    response.headers['Status'].to_i.should == 404
  end

  it 'should 404 without a post id' do
    get :index, :user_id => 2
    response.headers['Status'].to_i.should == 404
  end
end

Obviously there's a little bit of duplication in the 404's. Let's define macro tests to clean that up.

describe 'GET /users/:user_id/posts/:post_id/comments' do
  def self.should_404_without(param)
    # Since you're calling this method within the describe block, 
    # it is being called within the correct context.
    it "should 404 without #{param}" do
      get :index, paramz.merge(param.to_sym => nil)
      response.headers['Status'].to_i.should == 404
    end
  end

  should_404_without "user_id"
  should_404_without "post_id"

  # Normally I put this at the bottom, only here to keep it close to the above.
  # This method is called by the test the macro test defines to hand off the params.
  def paramz
    {:user_id => 2, :post_id => 3}
  end

  it 'should be a success' do
    get :index, paramz
    response.should be_success
  end
end

Hmm... this doesn't really look any cleaner. The problem is that we did this for only one action. If we generalize should_404_without more, then we can put it into its own shared example set that we can include in any describe block. Let's look at that now.

shared_examples_for "controllers" do
  def self.should_normally_succeed
    it 'should be a success' do
      get @action, paramz
      response.should be_success
    end
  end
  
  def self.should_404_without(param)
    it "should 404 without #{param}" do
      get @action, paramz.merge(param.to_sym => nil)
      response.headers['Status'].to_i.should == 404
    end
  end
end

describe 'GET /users/:user_id/posts/:post_id/comments' do
  it_should_behave_like "controllers"
  
  before(:each) { @action = :index }

  should_normally_succeed
  should_404_without "user_id"
  should_404_without "post_id"

  def paramz
    {:user_id => 2, :post_id => 3}
  end
end

Oh snap! That describe block is a lot cleaner, and we can tuck the shared examples into spec_helper.rb to really clean things up. Using macro tests, you'll find it's very easy to create a lot of REST controllers very quickly. In fact, I plan on open sourcing something to help with that very soon...

Update: See the comments for David's advice on pulling this out of shared examples and into a module that you can then add to rSpec. This cleans up the describe blocks even more. Mega win!

Starting the Car

written by trotter on May 4th, 2008 @ 12:14 AM

Well, it's not much of a start, but every trip must have a beginning. As I wake up and wipe my bleary eyes, I'm going to slowly pull this car out of the driveway and put it on the road. The tunes aren't yet cranking; no Allman Brothers is yet helping us greet the open road. Still, we've left that old home that is lifecoding and are starting out on something new, something fresh. We're running on rubies with a comfortable walking shoe pushing the accelerator. I hope you enjoy this ride.

Options:

Size

Colors