Ho usato questo per consentire i nomi di "amici" in una tabella cetriolo per essere analizzati in classe attributi tale che Factory Girl potrebbe creare un'istanza:
Given(/^an organization exists with the following attributes:$/) do |table|
# Build a mapping from the "friendly" text in the test to the lower_case actual name in the class
map_to_keys = Hash.new
table.transpose.hashes.first.keys.each { |x| map_to_keys[x] = x.downcase.gsub(' ', '_') }
table.transpose.hashes.each do |obj|
obj.keys.each { |k| obj[map_to_keys[k]] = obj.delete(k) if map_to_keys[k] }
create(:organization, Rack::Utils.parse_nested_query(obj.to_query))
end
end
Per quello che vale, la tabella di cetriolo assomiglia a questo :
Background:
And an organization exists with the following attributes:
| Name | Example Org |
| Subdomain | xfdc |
| Phone Number | 123-123-1234 |
| Address | 123 E Walnut St, Anytown, PA 18999 |
| Billing Contact | Alexander Hamilton |
| Billing Address | 123 E Walnut St, Anytown, PA 18999 |
E map_to_keys
assomiglia a questo:
{
"Name" => "name",
"Subdomain" => "subdomain",
"Phone Number" => "phone_number",
"Address" => "address",
"Billing Contact" => "billing_contact",
"Billing Address" => "billing_address"
}
fonte
2015-01-04 14:59:28
Grazie, è fantastico! Ora, se voglio solo cambiare alcuni dei nomi delle chiavi, c'è un modo per verificare se esiste una mappatura per la chiave? – Chanpory
Basta usare 'mappings [k] || k' invece di 'mappings [k]' sopra e lascerà le chiavi non nella mappatura così com'è. –
Brillante! Grazie mille :-) – Chanpory