简体   繁体   English

在Rails中为email_uniqueness_index创建Rspec测试

[英]Creating Rspec Test for email_uniqueness_index in Rails

How can I write an Rspec test for the following? 如何为以下内容编写Rspec测试? Using TDD, I want to be able to write a test to that requires the following code in order to pass. 使用TDD,我希望能够编写一个测试,该测试需要以下代码才能通过。

class AddEmailUniquenessIndex < ActiveRecord::Migration
  def up
    add_index :users, :email, :unqiue => true
  end

  def down
    remove_index :users, :email
  end
end

Within your test, just try to create two users with same e-mail address. 在您的测试中,只需尝试创建具有相同电子邮件地址的两个用户。 Second one should not have valid email. 第二个不应该有有效的电子邮件。 Something like this: 像这样的东西:

it "prevents duplicates" do
  user1 = create(:user, email: 'unique@email.com')
  user2 = build(:user, email: 'unique@email.com')

  user1.should be_valid
  user2.should_not have_valid(:email)
end

Note that I'm using factory_girl and valid_attribute gems in the example above. 请注意,我用factory_girlvalid_attribute宝石在上面的例子中。 I'm also assuming that you have validates :email, uniqueness: true in your model. 我还假设您有validates :email, uniqueness: true在您的模型中为validates :email, uniqueness: true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM