嵌套表单的功能测试

时间:2013-02-25 00:02:06

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 nested-forms

我有2个型号:公司和用户。公司有很多用户,用户属于公司。 我创建了一个嵌套表单:当您注册时,您必须创建公司和第一个用户。

表单就像魅力一样,但我真的不知道怎么写测试。这里是脚手架生成的功能测试:

test "should create company" do
  assert_difference('Company.count') do
    post :create, company: { city: @company.city, name: @company.name}
  end
  assert_redirected_to company_path(assigns(:company))
end

这就是我为测试用户创建而做的事情:

test "should create company and first user" do
  assert_difference('Company.count') do
    assert_difference('User.count') do
      post :create, company: { city: @company.city, name: @company.name}, user: {name: @user.name, email: @user.email}
    end
  end
  assert_redirected_to company_path(assigns(:company))
end

当我运行测试时,会发生以下错误:

1) Failure:
test_should_create_company_and_first_user(CompaniesControllerTest) [test/functional/companies_controller_test.rb:21]:
"User.count" didn't change by 1.
<3> expected but was
<2>.

我没有在互联网上找到帮助,所以我希望有人可以这样做:)

2 个答案:

答案 0 :(得分:2)

如果表单实际上是嵌套的,那么您应该在测试请求中的公司对象中包含用户对象,如下所示:

post :create, company: { city: @company.city, name: @company.name, user: {name: @user.name, email: @user.email} }

答案 1 :(得分:0)

<强>解

公司模式

attr_accessible :city, :name, :users_attributes
has_many :users
accepts_nested_attributes_for :users

用户模型

attr_accessible :email, :name
belongs_to :company

公司控制器测试

test "should create company and first user" do
  assert_difference('Company.count') do
    assert_difference('User.count') do
      post :create, company: { 
        city: @company.city, 
        name: @company.name, 
        users_attributes: {
          user: {name: @user.name, email: @user.email}, 
          user: {name: @user.name, email: @user.email}
        }
      }
    end
  end
  assert_redirected_to company_path(assigns(:company))
end

您可以使用users_attributes中的一个或多个用户进行测试。

感谢@drewinglis的帮助:D