我是新的Ruby和Rspec。我正在写我的第一个RSpec测试,我认为我的代码不太好。但我不知道如何让它变得更好。DRS问题与Rspec我该如何解决它
在这个文件中,我将检查我的地址类。 first_name和last_name是相同的,但我有两个大块。我如何重构我的代码?什么是检查RegExp的好方法。
谢谢。
specify { Factory.build(:address).should be_valid }
### first_name ###
it "should be invalid without an first_name" do
Factory.build(:address, :first_name => nil).should_not be_valid
end
context "first_name" do
it "should be invalid with more than 20 chars" do
Factory.build(:address, :first_name => "#{'b'*21}").should_not be_valid
end
it "should be invalid with less than 3 chars" do
Factory.build(:address, :first_name => "ll").should_not be_valid
end
it "should be valid with an valid first_name" do
valid_names.each do |name|
Factory.build(:address, :first_name => name).should be_valid
end
end
it "should be invalid with an invalid first_name" do
invalid_names.each do |name|
Factory.build(:address, :first_name => name).should_not be_valid
end
end
end
### last_name ###
it "should be invalid without an last_name" do
Factory.build(:address, :last_name => nil).should_not be_valid
end
context "last_name" do
it "should be invalid with more than 20 chars" do
Factory.build(:address, :last_name => "#{'b'*21}").should_not be_valid
end
it "should be invalid with less than 3 chars" do
Factory.build(:address, :last_name => "ll").should_not be_valid
end
it "should be valid with an valid last_name" do
valid_names.each do |name|
Factory.build(:address, :last_name => name).should be_valid
end
end
it "should be invalid with an invalid last_name" do
invalid_names.each do |name|
Factory.build(:address, :last_name => name).should_not be_valid
end
end
end
def valid_names
["Kai","Ülück's","Schmeißtzs","Rald","Dr. Franzen","rolfes","Lars Michael","Öcück","Mark-Anthony"]
end
def invalid_names
["-#+*32"," ","a& &lkdf","_-_.l##df"," aaadsa","M€lzer"]
end
我会用本发明的方法对于这一点,就像它在这里完成:https://github.com/rspec/rspec-expectations/blob/master/features/expectations/attribute_of_subject.feature – iain 2010-12-10 23:43:44
谢谢您为您的帮助 – ThreeFingerMark 2010-12-13 22:37:19