Rspec验证测试更新

时间:2013-12-11 18:13:43

标签: ruby-on-rails validation rspec

晚安编程员,

我正在慢慢尝试使用Rspec,我的大多数验证都是在创建用户之后发生的,正如您在下面的验证中所看到的,到目前为止这是整个验证部分。

 #validations for common attributes

 validates :email, presence: true, on: :create, uniqueness: true,
           :format => /@/
 validates :password, presence: true, on: :create, length: {minimum: 6}

 #validations blocks for dev

with_options :if => lambda { |o| o.role_type == "developer" } do |dev|
  dev.validates :first_name, presence: true, on: :update
  dev.validates :last_name, presence: true, on: :update
  dev.validates :languages, presence: true, on: :update
  dev.validates :dev_desc, presence: true, on: :update
  dev.validates :github, presence: true, on: :update, 
                :format => URI::regexp(%w(http https github))
  dev.validates :stackoverflow, presence: true, on: :update, 
                :format => URI::regexp(%w(http https stackoverflow))
  dev.validates :level, presence: true, on: :update
   dev.validates :street, presence: true, on: :update
   dev.validates :city, presence: true, on: :update
   dev.validates :state, presence: true, on: :update
   dev.validates :postcode, presence: true, on: :update
end

#validations block for employer

with_options :if => lambda { |o| o.role_type == "employer" } do |e|
    e.validates :company_name, presence: true, on: :update,
                uniqueness: true
    e.validates :employer_desc, presence: true, on: :update
    e.validates :area_of_focus, presence: true, on: :update
    e.validates :number_of_employees, presence: true, on: :update
 e.validates :street, presence: true, on: :update
 e.validates :city, presence: true, on: :update
 e.validates :state, presence: true, on: :update
 e.validates :postcode, presence: true, on: :update
end

现在我的当前测试失败了:

    it "should not be valid with blank firstname" do
        dev.first_name = ' '
        dev.should_not be_valid
    end

如果用户不完全有效,则会将用户重定向到编辑页面。我不明白为什么不通过。我将它扭曲并将其更改为 should ,它通过了测试。

有人可能会解释为什么它会通过,这里是dev的块:

let(:dev) { FactoryGirl.create :dev }

更新:这是我的工厂,不知道这会如何影响错误:

factory :dev, class: User do
    first_name { Faker::Name.first_name }
    last_name  { Faker::Name.last_name }
    email { Faker::Internet.email }
    password "12345678"
    password_confirmation "12345678"
    role_type "Developer"
    dev_desc "New to development but trying to help the community"
    github "www.github.com"
    stackoverflow "www.stackoverflow.com"
    languages "Rails"
    level     "Junior"
    street    {Faker::Address.street_address}
    city      {Faker::Address.city}
    state    {Faker::Address.state}
    postcode {Faker::Address.zip_code}
end

感谢您的帮助尝试理解这一点,因为验证在注册后可以手动完成。

2 个答案:

答案 0 :(得分:1)

first_name的验证取决于role "developer",但您的工厂将role设置为"Developer",因此未应用验证

答案 1 :(得分:0)

将验证更改为

dev.validates :first_name, presence: true, allow_blank: => false,  on: :update

默认情况下,状态验证允许空值