18
votes

I've been trying to get a grasp on writing tests, but having a lot of trouble as the tests never seem to validate the way I want them to. In particular, I've been trying to use Factory Girl as opposed to fixtures - as suggested by a recent Railscasts and other advice I've seen on the net - due to the benefits it professes, and that hasn't worked out.

For example, here is a simple Rspec test for a user model, testing to make sure a username is present...

describe User do
  it "should not be valid without a username" do
    user = FactoryGirl.create(:user, :username => "", :password => "secret")
    user.should_not be_valid
  end
end

And my factories.rb file, if it helps...

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "registered-#{n}" }
    password "foobar"
  end
end

When I run 'rake spec,' it tells me...

1) User should not be valid without a username
     Failure/Error: user = FactoryGirl.create(:user, :username => "", :password => "secret")
     ActiveRecord::RecordInvalid:
       Validation failed: Username can't be blank

Ummm...that's the POINT. If I specified that the user should NOT be valid, shouldn't this test actually pass?

If I replace the Factory Girl line and set the user in the test with something like 'user = User.new(:username => "", :password => "secret")', to no surprise the test passes fine. So why is Factory Girl not working right?

1

1 Answers

22
votes

You should use build like in the following:

user = Factory.build(:user, :username=>"foo")

Because using the method you're using will try to create a record. See docs for further information.