I have a model Position with a field started_at and ended_at, both of which are datetime fields. Because the date part of both have to be the same, I have a datetime_select form field for started_at but only a time_select ignore_date: true for ended_at. In the create method I’d like to assign the date values of started_at to ended_at like this:
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)"]
But this broke my controller specs, because there I assign the values directly:
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
So I ended up with this, but I’m not sure whether it is a reasonable fix:
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
Maybe there’s a better solution? Thanks for your opinions.
If the controller is expecting the attributes in a specific format, the spec should supply them in that format. Adjust
valid_attributesso that it separates the date and time elements in the same way that the form does, and the spec should pass.