0

我有一个带有帐户注册表单的 Rails 应用程序,在创建帐户的同时还创建了一个管理员用户。

新方法的控制器代码很简单

  def new
    @account = Account.new
    @account.users.build
  end

在 create 方法中,两个模型通过以下方式进行验证和创建

  def create
    @account = Account.new(params[:account])
    @account.status = "signup"
    if @account.save
      #find the user
      user = User.where("account_id =?", @account.id).first
      role = Role.where("rolesymbol =?", "admin").first
      @authorization = Authorization.new
      @authorization.role_id = role.id
      @authorization.user_id = user.id
      @authorization.save
    else
      render action: "new"
    end
  end

在实践中,这一切都很好。但是,我不知道如何在 rspec 控制器测试中构建用户。我已经尝试过

  describe "POST 'create'" do
    it "should create if all the details are correct" do
      account_params = FactoryGirl.attributes_for(:account)
      user_params = FactoryGirl.attributes_for(:user)
      post :create, :account => account_params, ;user => user_params
    end

但是,正如代码所示,这只是将两个模型按顺序排列,而不是将用户作为帐户的一部分。

有没有人做过类似的事情?

4

1 回答 1

0

好的,我解决了这个问题。因此,在一个模型的控制器规范中,该模型在一个表单中构建了两个模型。

控制器规格应该是

post :create, :account => attributes_for(:account).merge(users_attributes: [ attributes_for(:user) ])
  response.should redirect_to "http://test.host/subscribe/subcode/1/user-2"

很抱歉之前对错误所在位置的描述不佳,但希望这可以帮助遇到同样问题的其他人

于 2013-09-14T13:37:29.000 回答