FactoryGirl,2次创建用户?

时间:2012-12-19 20:59:02

标签: ruby-on-rails-3 rspec factory-bot

我真的不明白做出帮助。在spec_helper我有

def log_in_user
  user = User.find_by_name 'User1'
  user = FactoryGirl.create :user1 unless user
  sign_in user
end
rspec中的

let(:product) { FactoryGirl.build :product_A }


describe "GET confirm purchase" do
    it "xxx" do
      log_in_user

      Product.should_receive(:find_active_by_id).with("1").and_return(product)

       ...
   end
end

factories.rb

FactoryGirl.define do
    factory :user do
        encrypted_password 'abcdef1'
        confirmed_at Time.now

            factory :user1 do
              email 'user1@test.com'
              name 'User1'
              year 1984
            end
    end

    factory :product do
        factory :product_A do
          name "product A"
          association :user, factory: :user1
        end
    end
end

当我运行测试用例时发生异常: ActiveRecord :: RecordInvalid:验证失败:已经发送电子邮件

看起来user1正在创建2次,一次在log_in_user中,第二次在factory中:association:user,factory :: user1

我是对的?如果是,我该如何解决?我想创建用户并在工厂产品中定义协议

最好的

1 个答案:

答案 0 :(得分:2)

当您出厂:product_A时,它会自动调用:user1的工厂。

然后您在:user1中再次出厂log_in_user,但对唯一电子邮件的验证阻止了第二个:user1的创建。

我建议你像sequence那样发电子邮件:

FactoryGirl.define do
  sequence :email do |n|
    "user#{n}@test.com"
  end

  factory :user do
    encrypted_password 'abcdef1'
    confirmed_at Time.now

    factory :user1 do
      email
      name 'User1'
      year 1984
    end
  end

  factory :product do
    factory :product_A do
      name "product A"
      association :user, factory: :user1
    end
  end

end

然后,我会改变sign_in_user以取一个(可选的)用户作为这样的选项:

def log_in_user(user)
  user =|| User.find_by_name 'User1'
  user =|| FactoryGirl.create :user1
  sign_in user
end

修改测试用例以将该用户对象传递给login:

let(:product) { FactoryGirl.build :product_A }

describe "GET confirm purchase" do
  it "xxx" do
    log_in_user(product.user)
    Product.should_receive(:find_active_by_id).with("1").and_return(product)
 end
end