Do fixtures trigger model callbacks?

后端 未结 2 1692
旧时难觅i
旧时难觅i 2020-12-15 19:52

Say I have a User model with the following code in User.rb:

before_create :create_dependencies
after_create :build_inbox

And I also have a

相关标签:
2条回答
  • 2020-12-15 20:24

    Is this how it is expected to work? If so, why did they design it this way?

    Yes, fixtures do not use callbacks. I'm assuming this is for performance reasons. It is quicker to load the data straight into the database without instantiating the model.

    Is there a way to force the triggering of the callbacks when loading fixtures?

    Not that I know of. You have a couple options. One is to build your fixtures as if the callbacks were already triggered. That is, manually create the data that the callbacks would. For example, if you have a callback which hashes a user's password you would need to hash the password manually and then store that hash in the fixture.

    The second solution (and highly recommended!) is to use factories. Factories do trigger callbacks and allow you to use virtual attributes, etc. This is because they do instantiate the model each time. One popular gem is Factory Girl. Another one to try is Machinist. I have also created a Railscasts episode on the topic.

    0 讨论(0)
  • 2020-12-15 20:37

    I have this problem as well. Our app calculates some totals before_save so it doesn't have to be done on the fly. Makes reporting faster and cuts out a few joins on certain reports.

    In the tests for those objects we manually run the callbacks like this:

    before do
      order.perform_callbacks
    end
    

    This works out well because it doesn't run all the time so other tests don't suffer.

    We are using minitest and fixtures btw.

    0 讨论(0)
提交回复
热议问题