I am working on improving my company's RSpec tests (which have gotten a bit slow), and I suspect one of the culprits is a FactoryBot factory we use in almost every test - a factory that results in a bunch of unnecessary associations due to chaining. For example:
FactoryBot.define do
# we use a bunch of these and most tests don't care about the value of :b,
# but ActiveRecord validations require it
factory :A do
association :b
# some other attributes with simple types
end
factory :B do
association :c
end
factory :C do
association :d
end
end
How can I create an instance of A
without also forcing a B
, a C
, and a D
to get created (I am planning on controlling those with traits)? Using a build_stubbed
strategy has been my best answer so far (which doesn't solve all my problems, but is pretty good), but I am curious whether there are other tricks I could shove up my sleeves.
The problem is most likely how you create the model, and not because of FactoryBot. Let's say you have factory a with association b, c and d. In order to create the model you need all associations because you have a not null dependency, in the factory file you can add the following:
FactoryBot.define do
factory :a do
b { build :b }
c { build :c }
d { build :d }
end
end
Build let you persists the association in the memory database instead of the test database, however if you are doing a specific call to that association in the code which requires a database call, for example abupdate:(some_column: value)
you need to override it in the test by creating it like so create:a, b: create(:b)
.
It's also common for people to create the model every time instead of using let
, which only creates the object whenever you need it instead of in a before:each
for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.