1
Ben rails4, factory_ girl, rspec ve shoulda matchers kullanıyorum. Bu hatayı alıyorum aşağıdaki I koduyla RSpec çalıştırırsanız:Web sitesi biçimi doğrulama ile RSpec başarısız olur
Product should validate that :website cannot be empty/falsy, producing a custom validation error on failure
Failure/Error: self.website = "http://#{self.website}" unless self.website[/^https?/]
NoMethodError:
undefined method `[]' for nil:NilClass
ben format_website
yönteminden unless self.website[/^https?/]
silerseniz bu hatayı alıyorum:
Product did not properly validate that :website cannot be empty/falsy,
producing a custom validation error on failure.
After setting :website to ‹nil› -- which was read back as ‹"http://"›
-- the matcher expected the Product to be invalid and to produce a
validation error matching ‹/can't be blank/› on :website. The record
was indeed invalid, but it produced these validation errors instead:
* user: ["can't be blank"]
* name: ["can't be blank"]
* company: ["can't be blank"]
Ben bu işi yapmak için ne yapmalıyım?
ürün modeli
belongs_to :user
validates :name, presence: { message: "can't be blank" }, length: { maximum: 140, message: "can't be longer than 140 characters" }, uniqueness: { message: "already exists" }
validates :company, presence: { message: "can't be blank" }, length: { maximum: 140, message: "can't be longer than 140 characters" }
validates :website, presence: { message: "can't be blank" }, length: { maximum: 140, message: "can't be longer than 140 characters" }
before_validation :format_website
validate :website_validator
def format_website
self.website = "http://#{self.website}" unless self.website[/^https?/]
end
def website_validator
self.errors.add :website, "format is invalid!" unless website_valid?
end
def website_valid?
!!website.match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-=\?]*)*\/?$/)
end
fabrika
FactoryGirl.define do
factory :product do
name { Faker::Commerce.product_name }
company { Faker::Company.name }
website { 'https://example.com' }
user
end
end
it { is_expected.to callback(:format_website).before(:validation) } #this one is not important, if I take out it still gives the same error
it { is_expected.to validate_presence_of(:name).with_message(/can't be blank/) }
it { is_expected.to validate_presence_of(:company).with_message(/can't be blank/) }
it { is_expected.to validate_presence_of(:website).with_message(/can't be blank/) }
it { is_expected.to belong_to(:user) }
born4new, Bu soruyu düzgün bir şekilde sormadım. Doğrulayıcıyı yapmak için bu sorunu nasıl çözebileceğimi bilmek isterim. Başka tür bir doğrulama kullanmalı mıyım? –
Yine, soruna neden olan özellikleri görmeden söylemek zor, ama eminim ki FactoryGirl ile modelinizi oluşturduğunuzda, 'website' özniteliğini oluşturmazsınız. Öyleyse yap ve tamir etmeli. – born4new
born4new, Soruyu fabrikada güncelledim. –