如何在rails 3.1.0中以多对多方式连接rspec记录

时间:2012-01-18 04:20:02

标签: ruby-on-rails ruby-on-rails-3.1 rspec2

这是rfq控制器中的创建:

  def create
    if has_create_right?
      @rfq = Rfq.new(params[:rfq], :as => :roles_new )
      #save into join table rfqs_standards
      params[:rfq][:standard_ids].each do |sid|
        @rfq.standards << Standard.find(sid.to_i) if !sid.nil?
      end
    if @rfq.save
        redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
      else
        flash.now[:error] = "RFQ not saved!"
        render 'new'
      end
    end
  end

这是rspec代码

  describe "'create'" do
    it "should be successful for corp head" do
      session[:corp_head] = true
      session[:user_id] = 1
      s = Factory(:standard)
      rfq = Factory.attributes_for(:rfq)
      rfq.standards << s
      get 'create', :rfq => rfq
      response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
    end
  end

错误是:

  1) RfqsController 'create' should be successful for corp head
     Failure/Error: rfq.standards << s
     NoMethodError:
       undefined method `standards' for #<Hash:0x6741570>
     # ./spec/controllers/rfqs_controller_spec.rb:65:in `block (3 levels) in <top (requi

测试联接记录的正确方法是什么?感谢。

1 个答案:

答案 0 :(得分:1)

从测试的这一部分开始:

    rfq = Factory.attributes_for(:rfq)
    rfq.standards << s

似乎rfq是作为属性哈希创建的,而不是完整的模型。您可以尝试加入standard_ids,如下所示:

describe "'create'" do
  it "should be successful for corp head" do
    session[:corp_head] = true
    session[:user_id] = 1
    s = Factory(:standard)
    rfq = Factory.attributes_for(:rfq)
    rfq[:standard_ids] = [s.id] # attach standard_id's to mimic the POST'ed form data
    get 'create', :rfq => rfq
    response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
  end
end

但是,您似乎可以使用嵌套属性完成所有这些操作 - 请参阅http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html