Could someone please explain why Factories are more useful than a simple instantiation during test? More clearly, I do not see the difference between:
before(:each) do
@attr = {
:name => "Example User",
:email => "user@example.com",
:password => "foobar",
:password_confirmation => "foobar"
}
end
it "should create a new instance given valid attributes" do
User.create!(@attr)
end
and this
before(:each) do
@user = Factory(:user)
end
which has the following Factory:
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
Because it lets you have in a single place all your required variables plus associations.
Moreover, you can easily create stubs or simply extract attributes without additional code.
The interest is clearer once you have several test files as you want to keep your code DRY.
Sidenote:
You should use ‘let’ instead of creating each time an instance variable