Rails 3 plants versus simple creation

Can someone explain why factories are more useful than just instantiating during a test? More clearly, I see no 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 one

 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 
+4
source share
2 answers

Because it allows you to have all the necessary variables and associations in one place.

In addition, you can easily create stubs or simply retrieve attributes without additional code.

Interest becomes clearer if you have several test files, since you want to keep your DRY code.

Sidenote:

You should use 'let' instead of creating an instance variable each time

+4
source

The more your application gets, the more benefits you get from factories.

Your solution is great for 2-3 models. But let's say you have an article model in which you need valid users for testing. You now have 2 files where you define @attr for users. Now imagine that there are even more models that users need, such as comments, roles, etc. It is getting messy.

It is more convenient to use factories. You can define several prototypes by default. As admin user, regular user, unregistered user, etc.

In addition, the code is DRY, so if you add a new required field, you can add it once to your factory, and you're done.

So, the answer is this: basically they are the same, but the larger your application, the more you need a way to manage all your prototypes.

+5
source

Source: https://habr.com/ru/post/1369358/


All Articles