jeudi 14 juillet 2016

How to test if a child record got created in Rails controller test?

I have the following controller test which tests if the user got created successfully. But I am not sure how to test if the child record (role) got created successfully or not.

Please guide.

users_controller_test.rb

    class UsersControllerTest < ActionController::TestCase
     test "should create user" do
        assert_difference('User.count') do
          post :create, user: { first_name: 'Controller User First Name', last_name:"Controller User Last Name", email: 'fisrtlast@email.com',
                                phone: '1111111111', time_zone: 'Eastern Time (US & Canada)', password: 'Password123',
                                password_confirmation: 'Password123', client_ids: '339762980', store_ids:['','248505843',''],
                                profile_id: '417269330'}, commit: 'Create User'
        end

        assert_redirected_to user_path(assigns(:user))
      end
   end

users_controller.rb

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)
    @user.locale = I18n.default_locale

    respond_to do |format|
      if @user.save
        @user.roles.concat(@user.profile.roles)
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

user.rb

class User < ActiveRecord::Base
  has_many :stores, through: :store_user_assignments
  belongs_to :profile
end

Aucun commentaire:

Enregistrer un commentaire