Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hartl's Rails Tutorial Chapter 9 Exercise 6

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 quite clear on the difference between the two actions "create" and "new" themselves either; could someone please be so kind as to elaborate?

After creating the test how would I go about implementing the redirect_to root_path? I think I am supposed to include the "new" and "create" actions in the before_filter signed_in section but this doesn't automatically redirect to the root.

I tried to get the tests to pass by modifying the users_controller.rb file as follows:

  def create
    if signed_in?
      redirect_to root_path
    else
      @user = User.new(params[:user])
      if @user.save
        sign_in @user
        flash[:success] = "Welcome to the Sample App!"
        redirect_to @user
      else
        render 'new'
      end
    end
  end
like image 261
railser Avatar asked Jun 20 '12 11:06

railser


1 Answers

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.

like image 172
rkrdo Avatar answered Sep 21 '22 06:09

rkrdo