使用RSpec测试嵌套控制器操作

时间:2011-11-08 07:12:58

标签: ruby-on-rails unit-testing rspec

我设置的路线如下:

match '/things/:thing_id' => "descriptions#index", :as => :thing
resources :things, :except => [:show] do 
  ...
  resources :descriptions, :only => [:create, :index]
end

如何测试嵌套描述的:create方法?

到目前为止我已经

context "with user signed in" do

  before(:each) do
    user = Factory.create(:user, :name => "Bob")
    controller.stub!(:authenticate_user!).and_return(true)
    controller.stub!(:current_user).and_return(user)
  end

  describe "PUT create" do

    before(:each) do
      @thing = Factory.create(:thing)
      params = {"text" => "Happy Text"}

      post thing_descriptions_path(@thing.id), params  #Doesn't work
      post :create, params                             #Doesn't work

    end
  end
end

1 个答案:

答案 0 :(得分:3)

以下内容应该有效:

describe "PUT create" do

  before(:each) do
    @thing = Factory(:thing)
    attrs = FactoryGirl.attributes_for(:description, :thing_id => @thing)

    post :create, :thing_id => @thing, :description => attrs
  end
end

要创建嵌套资源,您需要告诉rspec post创建的父ID,以便它可以将其插入到路径中。

您还需要创建与:descriptions内置关系的:thing工厂,并将thing_id传递给:description属性创建,这是为了制作确保Factory Girl在创建:thing的属性时不会创建新的:description,虽然这不会导致测试失败,但会降低速度,因为您最终会创建:thing的两个实例。