Hartl's Rails Tutorial Chapter 9 Exercise 6

后端 未结 3 1718
逝去的感伤
逝去的感伤 2020-12-20 18:17

Updating, showing, and deleting users, exercises

Is there a way to create an Rspec test for User controller actions such as \"create\" and \"new?\"

I\'m not

相关标签:
3条回答
  • 2020-12-20 18:42

    I did a before filter for that, seems to work well, for the test I did this:

    on authentication_pages_spec.rb

    describe "signin" do
      describe "authorization" do
        describe "for signed in users" do
          let(:user) { FactoryGirl.create(:user) }
          let(:new_user) { FactoryGirl.attributes_for(:user) }
          before { sign_in user }
    
          describe "using a 'new' action" do
            before { get new_user_path }
            specify { response.should redirect_to(root_path) }
          end
    
          describe "using a 'create' action" do
            before { post users_path new_user }
            specify { response.should redirect_to(root_path) }
          end         
        end
      end
    end
    

    Like @WillJones says, some people might have to add no_capybara: true to the before block

    and on my users controller:

    before_filter :signed_in_user_filter, only: [:new, :create]
    
    def signed_in_user_filter
      redirect_to root_path, notice: "Already logged in" if signed_in?
    end
    

    For the difference between the new and create actions, it has to do with the REST architectural style, but basically, new is an action from users controller that responds to a GET request and is the one that's in charge of returning the view it responds to (in this case, a new user form). create on the other hand, is an action that responds to a POST request, it doesn't render anything (it can respond with javascript, but that's an advanced topic) and it's the one responsible for creating new users, like the action's name implies.

    0 讨论(0)
  • 2020-12-20 18:49
    1. Yes; and this is partially begun around 7.16 and elsewhere.
    2. One actually creates a user (create). One is for the page for creating a new user (new).
    3. Not sure I understand the question.
    0 讨论(0)
  • 2020-12-20 18:55

    I did a before filter for that too, but my filter is different and I don't understand why it works.

    My users controller has following entries

       class UsersController < ApplicationController
    .
    .
      before_filter :logged_in_user, only: [:new, :create]
    .
    .
    def logged_in_user
          redirect_to(root_path) if !current_user?(@user)
      end
    

    It works just fine as in rkrdo's example and corresponding tests pass. But does it mean that current_user is not the same as a user when user is signed-in and conversely? In my opinion they should be equal in first case and shouldn't in second.

    0 讨论(0)
提交回复
热议问题