我有以下控制器测试,用于测试用户是否成功创建。但我不确定如何测试子记录(角色)是否成功创建。
请指导。
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
用户.rb
class User < ActiveRecord::Base
has_many :stores, through: :store_user_assignments
belongs_to :profile
end
如果计数差异相同(即 1),您可以这样做:
assert_difference(["User.count", "Role.count"], 1) do
...
end
否则,如果它更复杂,您可以查看本教程