Say I have a User and Post model, a has_many user message, and a post belongs_to .
When I write the spec for Post , my first instinct is to write something like this:
before do @user = FactoryGirl.create :user @post = @user.posts.new(title: "Foo", content: "bar) end ... tests for @post go here ...
But this will lead to the creation of a new user - getting into the database - for each individual test, which slows down the work. Is there a better way to do this to speed up my tests and avoid getting into the database often?
As I understand it, I can not use FactoryGirl.build :user , because although it does not get into the database, associations will not work properly, because @user will not have an identifier, and therefore @post.user will not work ( it returns nil .)
I could use FactoryGirl.build_stubbed :user , who created a "fake saved" @user that has an ID, but @post.user still returns nil. Does build_stubbed have any practical advantage over build when I test things related to associations?
Suppose I could use build_stubbed stub @post.user to return @user ... is there any reason this might be a bad idea?
Or do I just need to use create and accept the speed?
The only alternative I can think of would be to set @user in a before(:all) block, which looks like a bad idea.
What is the best way to write these tests in a clean, concise way that allows you to make too many database queries?
ruby-on-rails unit-testing rspec factory-bot
Gma
source share