Rails的fixture文件在传递给YAML解析之前先用ERB解析,这样一来我们就可以使用Ruby代码动态生成测试数据,而不用一条数据一条数据的写了:
[code]
<% 1.upto(50) do |number| %>
child_post_<%= number %>:
id: <%= number + 3 %>
title: This is auto-generated reply number <%= number %>
body: We're on number <%= number %>
created_at: 2006-01-30 08:03:56
updated_at: 2006-01-30 08:03:56
<%# Randomly choose a parent from a post we've already generated -%>
parent_id: <%= rand(number - 1) + 1 %>
user_id: <%= rand(5) + 1 %>
<% end %>
[/code]
我们还可以定义一些helper方法:
[code]
<%
def today
Time.now.to_s(:db)
end
def next_week
1.week.from_now.to_s(:db)
end
def last_week
1.week.ago.to_s(:db)
end
post_from_last_week:
id: 60
title: pizza
body: Last night I had pizza. I readlly liked that story from AWDWR.
created_at: <%= last_week %>
updated_at: <%= last_week %>
user_id: 1
post_created_in_future_should_not_display:
id: 61
title: Prognostication
body: I predict that this post will show up next week.
created_at: <%= next_week %>
updated_at: <%= next_week %>
updated_post_displays_based_on_updated_time:
id: 62
title: This should show up as posted today.
body: blah blah blah
created_at: <%= last_week %>
updated_at: <%= today %>
user_id: 2
[/code]
[code]
<% 1.upto(50) do |number| %>
child_post_<%= number %>:
id: <%= number + 3 %>
title: This is auto-generated reply number <%= number %>
body: We're on number <%= number %>
created_at: 2006-01-30 08:03:56
updated_at: 2006-01-30 08:03:56
<%# Randomly choose a parent from a post we've already generated -%>
parent_id: <%= rand(number - 1) + 1 %>
user_id: <%= rand(5) + 1 %>
<% end %>
[/code]
我们还可以定义一些helper方法:
[code]
<%
def today
Time.now.to_s(:db)
end
def next_week
1.week.from_now.to_s(:db)
end
def last_week
1.week.ago.to_s(:db)
end
post_from_last_week:
id: 60
title: pizza
body: Last night I had pizza. I readlly liked that story from AWDWR.
created_at: <%= last_week %>
updated_at: <%= last_week %>
user_id: 1
post_created_in_future_should_not_display:
id: 61
title: Prognostication
body: I predict that this post will show up next week.
created_at: <%= next_week %>
updated_at: <%= next_week %>
updated_post_displays_based_on_updated_time:
id: 62
title: This should show up as posted today.
body: blah blah blah
created_at: <%= last_week %>
updated_at: <%= today %>
user_id: 2
[/code]