【问题标题】:How to test if a child record got created in Rails controller test?如何测试是否在 Rails 控制器测试中创建了子记录?
【发布时间】:2016-07-14 15:41:34
【问题描述】:

我有以下控制器测试,用于测试用户是否成功创建。但是我不确定如何测试子记录(角色)是否成功创建。

请指导。

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec


    【解决方案1】:

    如果计数的差异相同(即 1),您可以这样做:

    assert_difference(["User.count", "Role.count"], 1) do
      ...
    end
    

    否则,如果它更复杂,你可以看看这个tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多