can_has_fixtures

Easily create fixtures.

Author

Ben Burkert ([email protected])

Version

0.1.1

Copyright

Copyright © 2008 Ben Burkert. All rights reserved.

License

New BSD License (opensource.org/licenses/bsd-license.php)

Website

canhasgems.rubyforge.org/can_has_fixtures

Repository

git://github.com/benburkert/can_has_fixtures.git

Dependencies

Basic Usage

can_has_fixtures works with any ORM that provides a create method that accepts an attribute hash on the model classes.

can_has_fixtures works best with RSpec, but can be used from irb as well:

require 'can_has_fixtures'

First create a fixture for the model, in this case it’s Post:

Post.fixture {{
  :title        => 3.random.words * ' ',
  :created_at   => Time.now,
  :body         => 5.random.paragraphs * '\n',
  :author       => User.gen
}}

If the a nested fixture is used (author, in this case), make sure to create add the fixture:

User.fixture {{
  :first_name   => Random.word,
  :last_name    => Random.word,
  :user_name    => Random.word,
  :email        => Random.email,
  :password     => Random.word
}}

Finally, call model class’ gen method to create the fixture:

@post = Post.gen

Fixtures can also be named by supplying the fixture method a paramater:

Post.fixture(:short_post) {{
  :title        => 3.random.words * ' ',
  :created_at   => Time.now,
  :body         => Random.sentence,
  :author       => User.gen
}}

@post = Post.gen(:short_post)

can_has_fixtures is great for specing models. By using the model’s class for the describe target, simply call fixture within the body of the spec:

describe Post do
  fixture {{
    :title        => 3.random.words * ' ',
    :created_at   => Time.now,
    :body         => Random.sentence
  }}

  before(:each) do
    @post = Post.gen
  end

  it "should not be valid without a body" do
    @post.body = nil
    @post.save

    @post.should_not be_valid
  end
end