I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.json { render json: @user, status: :created }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
I am able to successfully use this action from JavaScript with Ajax. Now I am attempting to test this action with the following code:
test "should create user" do
assert_difference('User.count') do
post "/users.json", user: { email: @user.email, name: @user.name }
end
end
However, when I run the test, it throws an error:
1) Error: UsersControllerTest#test_should_create_user: ActionController::UrlGenerationError: No route matches {:action=>"/users.json", :controller=>"users", :user=>{:email=>"MyString", :name=>"MyString"}} test/controllers/users_controller_test.rb:16:in 'block (2 levels) in ' test/controllers/users_controller_test.rb:15:in 'block in '
So my inquiry is, how can I effectively test an action that responds in json format? And why does the path /users.json
work seamlessly in my application but is not recognized during testing?