code tunes

Web applications, software engineering, Ruby on Rails, Cake PHP, JavaScript, etc.

Fixtures without validation with Factory Girl

Factory Girl is my fixture replacement library of choice. It improves tests readability and maintainability. It’s also customizable.

There are sometimes situations when you want to create test scenarios that checks how your app is handling invalid data (not user input, but invalid records that already sit in your database). To do this you first need to put this invalid data to your db.

You could accomplish this with such line:

@user = Factory(:user, :email => "not a correct email address")

However, factory girl would raise an exception here, because that’s the default strategy of creating new fixtures - raise exception if save fails (because of validation errors for example).

Thankfully we can use our own strategy of creating new fixtures, such that does save records without validation.

First let’s define our new strategy:

class Factory::Proxy::CreateWithoutValidation < Factory::Proxy::Build
  def result
    @instance.save(false)
    @instance
  end
end
 
class Factory
  def self.create_without_validation (name, overrides = {})
    factory_by_name(name).run(Proxy::CreateWithoutValidation, overrides)
  end
end

Now we can use it while defining new factory:

Factory.define :invalid_user, :class => User, :default_strategy => :create_without_validation do |f|
  ...
end

And then we can happily create invalid fixtures without any exceptions raised.

Related posts

4 comments

Written by Michał Szajbe

November 5th, 2009 at 2:29 pm

4 Responses to 'Fixtures without validation with Factory Girl'

Subscribe to comments with RSS

  1. Nice tip, thanks!!

    Michael Dvorkin

    7 Nov 09 at 03:36

  2. Hey!

    Nice tip! But in what file do you put the strategy?

    Johan

    15 Nov 09 at 17:41

  3. I usually keep strategies and factories in the same file.
    In larger projects I use different approach - each model has it’s own file with factories. I may write about it soon.

    Michał Szajbe

    16 Nov 09 at 00:11

  4. I have as you say, one factory file for each model. That seems to be the default for Factory Girl. That’s why I was wondering where to put the strategy, so that it would be shared between all factories.

    Johan

    16 Nov 09 at 09:46

Sorry, comments are closed for this post.