With rails 3 and rspec. I have a form in a view like this ..
<%= form_for current_account, { :url => admins_account_path(current_account), :method => 'put' } do %>
<div class="action">
<%= submit_tag "Save" %>
</div>
<table>
<tbody>
<% @accountships.each do |accountship| %>
<tr>
<td><%= check_box_tag "accountship_ids[]", accountship.id, accountship.admin? %></td>
<td><%= accountship.user.name %>
</tr>
<% end %>
</tbody>
</table>
<% end %>
And in the controller, I handle the PUT with this method in accounts#update_admin. This is all working as expected.
@account.assign_administrators params[:accountship_ids]
My question is how do I construct the parameters in rspec to test that controller action. What I have tried so far is not working. Here's my latest try that doesn't work.
before(:each) do
# code that generates the ids, I know this is working from other tests ..
.
.
.
@attr = {
:accountship_ids => [
@admin_accountship.id,
@not_admin_accountship.id,
@signed_in_user_accountship.id
]
}
end
it "should assign admin to users in the list" do
# what should I be passing in as @attr?
put :update_admins, :id => @account, :accountship_ids => @attr
Accountship.find(@admin_accountship.id).admin.should be开发者_如何学运维_true
Accountship.find(@owner_accountship.id).admin.should be_true
Accountship.find(@not_admin_accountship.id).admin.should_not be_true
end
All the tests I've been able to write that require values from the form checkbox collection are failing, and it's apparent that the whatever_accountship.admin attribute is not being updated when the rspec test is posting the data.
Thanks in advance!
EDIT
I stumbled onto the solution. The array shouldn't have been wrapped in a hash, and the values in the array literal needed to be converted to strings first, as below.
@attr = [
@admin_accountship.id.to_s,
@not_admin_accountship.id.to_s,
@signed_in_user_accountship.id.to_s
]
Anyone understand why they need to be strings when other tests I have can accept a full-blown object (no strings required)?
Also, what do I do to my question now that I know the answer?
It looks like you're assigning the params hash to an instance variable and then making a new hash with the first hash as the value and passing the whole mess in the put
statement, when all you need to do is pass the original params. Or in other words:
put :update_admins, :id => @account.id, @attr
EDIT
Sorry, long day. The params need to go into a single hash following the action, so:
put :update_admins, {:id=>@account.id}.merge(@attr)
EDIT 2
The hash syntax will work if you pass strings in the array:
@attr = {
:accountship_ids => [
@admin_accountship.id.to_s,
@not_admin_accountship.id.to_s,
@signed_in_user_accountship.id.to_s
]
}
If you want to resolve the question with your own answer, I think you can just create an answer and then accept it.
精彩评论