lllllll
lllllll

Reputation: 4845

FactoryGirl.create not increasing `.count` field

I had the same problem as Nick Rutten in this thread Rails Tutorial: RSpec test decoupling. I suspected the problem was the FactoryGirl.create() saving to the database, and thanks to @prusswan I fixed it. However I do not understand why these puts don't indicate different User.count.

This is the snippet I'm interested in:

describe "with valid information" do

  puts "Number of users pre-Factory:" + User.count.to_s
  let(:user){FactoryGirl.create(:user)}
  puts "Number of users post-Factory:" + User.count.to_s

  (...)

end

I get:

Number of users pre-Factory:0
Number of users post-Factory:0

But shouldn't I get instead?:

Number of users pre-Factory:0
Number of users post-Factory:1

Btw, the factory is defined (although not so relevant now) as:

FactoryGirl.define do
  factory :user do
    name "Example User"
    email "[email protected]"
    password "foobar"
    password_confirmation "foobar"
  end
end

I'm stuck trying to understand why the counter is not increasing, wasn't the problem that it did increase to start with? thank you

Edit using @derekyau's suggestions:

Right now I've got in this order:

it "print counter before let"
  puts "Number of users:" + User.count.to_s
end

let(:user){FactoryGirl.create(:user)}

it "print counter after let"
  puts "Number of users:" + User.count.to_s
end

However now I get both values 1:

Number of users:1
Number of users:1

Close but not there yet!

Edit 2

As explained by @Peter Alfvin here: Within a given RSpec describe block, does the order of let, before and it statements matter? . The order of let, before, it is pretty much established, regardless of the code. That, together with @derekyau's explanation closes the question.

Upvotes: 2

Views: 757

Answers (1)

derekyau
derekyau

Reputation: 2946

Good question, I think that let(:user) is lazily evaluated so it isn't actually called until you use it inside of an it block.

If you want to force it to be evaluated try let!

let!(:user) {FactoryGirl.create(:user)}

If you want to see it change try doing the puts inside of an "it block"

it "check user count" do
  puts User.count
end

You should see '1'

Upvotes: 7

Related Questions