Factory Girl怎么没有对独特属性进行排序?

dan*_*neu 11 rspec ruby-on-rails factory-bot

我的控制器规范失败,因为Factory Girl似乎正在创建非唯一用户,即使我对需要唯一的用户属性进行排序.

错误

  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
Run Code Online (Sandbox Code Playgroud)

控制器规格(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
Run Code Online (Sandbox Code Playgroud)

工厂

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
Run Code Online (Sandbox Code Playgroud)

当我使用时,为什么Factory Girl不对用户属性进行排序Factory.create :topic

dan*_*neu 29

rake db:test:prepare 似乎解决了这个问题.

不过不知道为什么.架构尚未更改.

  • db:test:prepare清空数据库.FactoryGirl的序列是特定于测试运行的 - 每次运行规范时它都从1(0?)开始.测试后数据丢失或因为它们被不正确地停止或者自己没有清理后发生这种错误(如果你把工厂创建的调用放在一个之前没有清理,你会系统地解决这个问题) (19认同)
  • 你应该用Bundler运行它:`bundle exec rake db:test:prepare` (3认同)