I'm using Rails 5 and minitest. How do I submit parameters in minitest to simulate a POST request where my model gets created? I have this test
test "do create" do
person = people(:one)
score = 10
post ratings_url, params: {rating[person_id]: person.id, rating[score]: score}
# Verify we got the proper response
assert_response :success
end
but the above results in the error
localhost:myapp davea$ rails test test/controllers/ratings_controller_test.rb
Running via Spring preloader in process 30344
/Users/davea/.rvm/gems/ruby-2.4.0/gems/activesupport-5.0.6/lib/active_support/dependencies.rb:293:in `require': /Users/davea/Documents/workspace/myapp/test/controllers/ratings_controller_test.rb:14: syntax error, unexpected ':', expecting => (SyntaxError)
url, params: {rating[person_id]: person.id, rating[score]: score
The only reason I named the POST parameters "rating[person_id]" and "rating[score]" is because that's what they are named when the form is rendered in Rails as HTML.
Edit: In response to the answer given, I tried this in my test
post ratings_url, params: { rating: { person_id: person.id, score: score} }
and the controller looks like
def save(params)
rating = Rating.new(rating_params)
rating.user = current_user
respond_to do |format|
and the error I got was
Error:
RatingsControllerTest#test_do_create:
ActionController::UnknownFormat: ActionController::UnknownFormat
Complaining about the line
respond_to do |format|
The hash-keys in your params hash are not valid.
params: {rating[person_id]: person.id, rating[score]: score }
You can't use rating[person_id] and use the newer hash-syntax/ you will need to use hash-rockets here eg:
params: {rating[person_id] => person.id, rating[score] => score }
This is assuming you have a local variable called rating with the keys in it...
If you aren't actually trying to get a value out of a local variable called rating... then you may need to be more detailed about your structure eg:
params: { rating: { person_id: person.id, score: score } }
of course... depending on which kind of test you are writing, you might need to not use ratings_url (also try it with and without the params key) eg:
post :ratings, params: { rating: { person_id: person.id, score: score } }
post :ratings, rating: { person_id: person.id, score: score }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With