2016-03-28 77 views
0

我想要一個簡單的方法來測試我的驗證。我的測試重點是集成,而不是驗證,我不使用TDD。話雖這麼說,我想替換:Rspec中測試驗證的簡短方法

# Estate model specs 

describe "#name" do 
    it "is required" do 
    estate.name = nil 
    estate.valid? 
    expect(estate.errors).to have_key(:name) 
    end 
end 

describe "#company" do 
    it "is required" do 
    estate.company = nil 
    estate.valid? 
    expect(estate.errors).to have_key(:company) 
    end 
end 

# and so on.. 

一些像:

# Estate model specs 

requiredFields = [:name, :company, :price, :region, :regions, :typologies, :image] 
requiredFields.each do |requiredField| 
    describe "##{requiredField}" do 
    it "is required" do 
     estate[requiredField] = nil 
     estate.valid? 
     expect(estate.errors).to have_key(requiredField) 
    end 
    end 
end 

的字段名稱和價格的作品,問題是在協會:

Estate 
    is an instance of Estate 
    validations 
    with required fields 
     should be valid 
    #name 
     is required 
    #company 
     is required (FAILED - 1) 
    #price 
     is required 
    #region 
     is required (FAILED - 2) 
    ... 

我認爲,問題是estate[requiredField]。如果我更改爲company_id將工作。我如何在foreach中做類似estate.requiredField的事情?

回答

2

可以使用Ruby的send方法,它調用它的參數作爲接收的方法進行estate.requiredField

estate.send(requiredField) 

既然你指派,你需要一個=插值到字段名。該foo=方法需要一個參數,它傳遞的持續參數send方法名稱後:

estate.send("#{requiredField}=", nil)` 

一個需要注意的是,由於send結束調用從接收機中的請求的方法,你可能最終繞過protectedprivate方法。

class Dog 
    private 
    def bark 
    puts 'Woof' 
    end 
end 

Dog.new.bark 
# NoMethodError: private method 'bark' called for #<Dog:0x007fd28bad7590> 

Dog.new.send :bark 
# Woof