使用RSpec,FactoryGirl和Rails 3.2构建后保存工厂

时间:2013-06-10 21:30:58

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

我有一个带有has_secure_password的帐户模型(自动创建2个attr_accessors:password和password_confirmation,在创建时需要)。我想在更新帐户对象时避免指定这些字段,因此我尝试使用RSpec和factoryGirl创建测试,如下所示:

describe Account do
    before do
        @account = FactoryGirl.build(:account) # this does not save the object
    end

    describe "password is not present (on update)" do
        before do
            @account.save
            @account.name = 'updated without specifying the password field'
        end
        it "should be valid" do
            should be_valid
        end
    end
end

但是,我最终得到了错误:

   Account password is not present (on update) should be valid
      Failure/Error: should be_valid
        expected valid? to return true, got false
      # ./spec/models/account_spec.rb:48:in `block (3 levels) in <top (required)>'

我无法使用FactoryGirl.create(:account),因为before block在许多其他测试之前执行,模型验证了电子邮件字段的唯一性。


如果我在块前的初始化中使用FactoryGirl.create(:account)(我现在使用序列生成器创建一个唯一的电子邮件地址)...此测试失败:

describe "email is already taken" do
    before do
      same_user = @account.dup
      same_user.email = @account.email.upcase # let's test against case sensitive strings
      same_user.save
    end

    it { should_not be_valid }
  end

这些是帐户模型中的一些验证:

 validates :name, :surname, presence: true
  validates :email, presence: true,
                    uniqueness: { case_sensitive: false },
                    format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
  validates :birthday, presence: true

  # Password validations
  validates :password, presence: true, :on => :create
  validates :password, length: { minimum: 4, maximum: 20 }, allow_blank: true
  validates :password_confirmation, presence: true, :unless => lambda { self.password.blank? }

1 个答案:

答案 0 :(得分:1)

每次使用工厂创建/建立帐户时,这都会生成一个唯一的电子邮件地址

sequence(:unique_email) {|n| "email#{n}@example.com" }
factory :account do
  email { generate(:unique_email) }
end

您不必保存对象以检查有效性

describe "email is already taken" do
    before do
      same_user = @account.dup
      same_user.email = @account.email.upcase # let's test against case sensitive strings
      same_user.valid?
    end

    it { should_not be_valid }
  end