【问题标题】:Rails test stack causing user validation to failRails 测试堆栈导致用户验证失败
【发布时间】:2013-12-28 17:21:37
【问题描述】:

更新:Forgery 生成的第一个电子邮件地址始终相同。随后的不同,但第一个总是相同的。我相信这可能是我的问题的原因。

我已经解决一个问题 3 天了,试图通过它来了解这些测试是如何工作的。但我不知所措。

我有一个用户模型和一个factory_girl 用户工厂。看起来像这样:

FactoryGirl.define do
  factory :user do
    sequence(:email)      { |n| Forgery(:internet).email_address }
    sequence(:company)    { |n| Forgery(:name).company_name }
    password              "password"
    password_confirmation "password"
    active                 true   
    admin false

    trait :admin do
      admin true
    end

    trait :inactive do
      active false
    end

  end

end

我有一堆规范要运行,我在处理它们时使用Guard 一次运行一个。在我的规格顶部,我有这行:

let!(:user) { login_user }

spec/support 中,我有一个名为login_macros.rb 的文件,如下所示:

module LoginMacros
  def login_user
    plan = FactoryGirl.create(:plan, name: "Test Multi")
    user = FactoryGirl.create(:user)
    subscription = FactoryGirl.create(:subscription, plan: plan) # Fails here
    visit login_path
    fill_in 'Email', :with => user.email
    fill_in 'Password', :with => user.password
    click_button 'Go'
    user
  end
end

看到上面以subscription = 开头的那一行了吗?失败并出现以下错误:

 Failure/Error: let!(:user) { login_user }
 ActiveRecord::RecordInvalid:
   Validation failed: Email has already been taken

我的Subscription 工厂是这样的:

FactoryGirl.define do
  factory :subscription do
  end
end

我不知道那个工厂是否正确。在我的应用程序中,Subscription belongs_to UserPlan。阅读完文档后,我仍然不清楚如果我使用 Forgery gem 会如何收到重复的电子邮件。有人可以帮忙吗?显然我不能再花时间在这上面了。

【问题讨论】:

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


    【解决方案1】:

    您的login_user 方法引用user 来指定电子邮件值,但不清楚user 的定义位置。我猜想它在每次连续调用此方法时都返回相同的值。如果不清楚您在哪里定义了user,您可能需要在login_user 的开头输出defined?(user) 以查看它是什么类型的对象。

    【讨论】:

    • 我在格式化过程中错误地删除了该行,我只是将其添加回来。谢谢你的收获。
    【解决方案2】:

    我能够通过将RSpecrspec-rails 强制升级到~> 2.14.0 并按照here 找到的指示来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      相关资源
      最近更新 更多