I’m up to the Chapter 9 Exercises in Hartl’s Rails Tutorial. I’ve been trying for ages but can’t crack question 6:
Signed-in users have no reason to access the
newandcreateactions in theUserscontroller. Arrange for such users to be redirected to the root URL if they do try to hit those pages.
First, where should I put these tests? At the moment I’m trying in user_pages_spec.rb but I’m unsure if that’s right. And then where should I put the logic itself?
Second, is this what my test should look like:
describe "after signing-in" do
before { sign_in(user) }
describe "creating a new user" do
before { put new_user_path }
specify { response.should redirect_to(root_url) }
end
end
At the moment when I do the above, RSpec tells me
Expected response to be a redirect to but was a redirect to http://www.example.com/signin.
But when I test it in my browser, visiting http://localhost:3000/users/new with a signed-in user, there is no redirect at all (which makes more sense to me because I haven’t coded one).
I’ve even downloaded Hartl’s code from github but I can’t see where / if he has included this functionality.
Edit:
I’ve got both
describe "creating a new user" do
before { visit new_user_path }
it { should_not have_selector 'title', text: full_title('Sign Up') }
end
And
describe "creating a new user" do
before { get new_user_path } # note the use of GET here not PUT
specify { response.should redirect_to(root_url) }
end
to work properly. Thanks to @Peter de Ridder for help
I’m not really sure why you have a put request when calling new_user_path.
Now the test should work as supposed. You still have to write the code to actually do the redirecting. But hey, that’s the whole challenge. Personally I would check if a user is signed in/present. If so, new and create actions should no longer be accessible.