我有一個模型Position
與字段started_at
和ended_at
,這兩個都是datetime
字段。由於兩者的日期部分必須相同,因此started_at
的表格字段爲datetime_select
,但ended_at
的表格字段僅爲time_select ignore_date: true
。在create
方法,我想的started_at
的日期值分配給ended_at
這樣的:檢查控制器的方法是從真實請求還是從控制器規格中調用?
params[:position]["ended_at(1i)"] = params[:position]["started_at(1i)"]
params[:position]["ended_at(2i)"] = params[:position]["started_at(2i)"]
params[:position]["ended_at(3i)"] = params[:position]["started_at(3i)"]
但是這打破了我的控制器的規格,因爲在那裏我直接分配值:
describe "POST create" do
describe "with valid params" do
it "creates a new Position" do
expect {
post :create, {:position => valid_attributes}, valid_session
}.to change(Position, :count).by(1)
end
end
end
所以我結束了這一點,但我不知道這是否是一個合理的修復:
if params[:position]["ended_at(1i)"].nil? and not params[:position]["started_at(1i)"].nil? # We have to check this because in the controller specs we assign the params directly (not in this crazy xxx_at(yi) form for dates), so by checking this we know that the data was sent through the form
params[:position]["ended_at(1i)"] = params[:position]["started_at(1i)"]
params[:position]["ended_at(2i)"] = params[:position]["started_at(2i)"]
params[:position]["ended_at(3i)"] = params[:position]["started_at(3i)"]
end
也許有更好的解決方案?感謝您的意見。
如果您正在測試控制器,使用將要在生產中發送的實際參數進行測試是否合理? – Gareth 2012-08-13 18:37:30