FactoryGirl和Rspec

Gal*_*axy 8 tdd rspec ruby-on-rails ruby-on-rails-3 factory-bot

我对这个TDD业务非常环保,所以任何帮助都会很棒!

所以,我有一家工厂,其中包括:

FactoryGirl.define do

  factory :account do
    email "example@example.com"
    url "teststore"
  end  

end
Run Code Online (Sandbox Code Playgroud)

和Rspec测试:

  it "fails validation without unique email" do
    account1 = FactoryGirl.create(:account)
    account2 = FactoryGirl.create(:account)
    account2.should have(1).error_on(:email)
end
Run Code Online (Sandbox Code Playgroud)

我收到以下消息失败:

  1) Account fails validation without unique email
     Failure/Error: account2 = FactoryGirl.create(:account)
     ActiveRecord::RecordInvalid:
       Validation failed: Email taken, please choose another, Url taken, please choose another
     # ./spec/models/account_spec.rb:11:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

这是创建新工厂的正确方法吗?我在这里做错了什么想法(我毫不怀疑我做错!)

编辑:我想的是,而不是在第二个帐户上使用"创建",我可能想要使用.build然后使用.save代替?

Fee*_*ech 15

保存自己的数据库交互,并在build这种情况下使用该方法.

it "fails validation without unique email" do
  account1 = create(:account)
  account2 = build(:account)
  account2.should_not be_valid
  account2.should have(1).error_on(:email) 
end
Run Code Online (Sandbox Code Playgroud)

您无需尝试创建帐户valid?以返回false.您可以访问帐户上的errors对象,即使它只是内置在内存中.这将减少数据库交互,从而使您的测试更快.

您是否考虑过在工厂中使用序列?我不知道您的RSpec/FactoryGirl经验有多远,但您会发现以下内容非常有用.

factories.rb

factory :account do
  sequence(:email) { |n| "user#{n}@example.com" }
  url "teststore"
end
Run Code Online (Sandbox Code Playgroud)

每次打电话buildcreate在工厂工厂,您都会收到独特的电子邮件.

请记住,您始终可以使用选项哈希为工厂中的属性指定值.因此,当您在帐户上测试您的唯一性验证时,您会执行类似的操作.

it "fails validation without unique email" do
  account1 = create(:account, :email => "foo@bar.com")
  account2 = build(:account, :email => "foo@bar.com")
  account2.should_not be_valid
  account2.should have(1).error_on(:email) 
end
Run Code Online (Sandbox Code Playgroud)