Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come Factory Girl isn't sequencing unique attributes?

My controller spec fails because Factory Girl seems to be creating non-unique Users even though I sequence the User attributes that need to be unique.

The Errors

  1) TopicsController POST #create when topic is invalid should render new
     Failure/Error: let(:invalid_topic) {Factory.build :invalid_topic}
     ActiveRecord::RecordInvalid:Validation failed: Email has already been taken, Username has already been taken

  2) TopicsController POST #create when topic is valid should redirect to show
     Failure/Error: let(:valid_topic) {Factory.build :topic}
     ActiveRecord::RecordInvalid:
       Validation failed: Email has already been taken, Username has already been taken

The Controller Spec (RSpec)

  describe "POST #create" do                          
    let(:valid_topic) {Factory.build :topic}
    let(:invalid_topic) {Factory.build :invalid_topic}

    context "when topic is invalid" do
      it "should render new" do
        post :create, :topic => invalid_topic
        response.should render_template(:new)
      end
    end
    context "when topic is valid" do
      it "should redirect to show" do
        post :create, :topic => valid_topic
        response.should redirect_to(topic_path(assigns(:topic)))
      end
    end
  end

The Factories

Factory.define :user do |f|
  f.sequence(:username) { |n| "foo#{n}"}
  f.password "password"
  f.password_confirmation { |u| u.password}
  f.sequence(:email) { |n| "foo#{n}@example.com"}
end

Factory.define :topic do |f|
  f.name "test topic"
  f.association :creator, :factory => :user
  f.forum_id 1
end

Why isn't Factory Girl sequencing the User attributes when I use Factory.create :topic?

like image 666
danneu Avatar asked May 22 '11 21:05

danneu


People also ask

What is Ruby Factory Girl?

Factory Girl provides a well-developed ruby DSL syntax for defining factories like user, post or any other object—not only Active Record objects.

What does Factory Girl do?

Young girls in mills worked with large machines to spin thread and to weave cloth.

What is factory Girl gem?

Gems like Factory Girl and Sham allow you to create templates for valid and re-usable objects. They were created in response to fixtures which where fixed records that had to be loaded into the database.


2 Answers

rake db:test:prepare seemed to fix the problem.

Not sure why, though. The schema hadn't been changed.

like image 79
danneu Avatar answered Sep 27 '22 17:09

danneu


Please, consider using database_cleaner gem. One was designed specifically to fulfill the purpose of cleaning up database between test runs.

This post explains pretty much everything.

like image 24
gmile Avatar answered Sep 27 '22 17:09

gmile