0

我尝试通过这两个创建控制器规范,但由于某种原因它没有验证Item对象。可能FactoryGirl.attributes_for(:item)是缺少必要的profile关联attachment吗?如果是这样,我怎样才能将它也传递给属性?

  describe "POST #create" do

    context "signed in" do 
      login_user

      context "with valid attributes" do 
        it "creates a new item" do
          expect{
            post :create, trend: FactoryGirl.attributes_for(:item)
            }.to change(Item,:count).by(1)
        end
        it "redirects to the home page" do 
          post :create, item: FactoryGirl.attributes_for(:item)
          response.should redirect_to Item.last 
        end
      end

    end

我收到了这些错误

Failures:

  1) ItemsController POST #create signed in with valid attributes creates a new item
     Failure/Error: expect{
       count should have been changed by 1, but was changed by 0
     # ./spec/controllers/items_controller_spec.rb:42:in `block (5 levels) in <top (required)>'

  2) ItemsController POST #create signed in with valid attributes redirects to the home page
     Failure/Error: response.should redirect_to Item.last
       Expected response to be a <redirect>, but was <200>
     # ./spec/controllers/items_controller_spec.rb:48:in `block (5 levels) in <top (required)>'

这是Item工厂

FactoryGirl.define do
  factory :item do
    profile

    after(:build) do |item|
      item.attachments << FactoryGirl.build(:attachment, attachable: item)
    end
  end

end
4

1 回答 1

1

我猜想 FactoryGirl.attributes_for 实际上并不是一个构建,所以 after(:build) 不会触发。这个怎么样:

FactoryGirl.attributes_for(:item, :profile_attributes => FactoryGirl.attributes_for(:profile), :attachments => [FactoryGirl.attributes_for(:subject)])

首先在rails控制台中尝试这条线可能是一个好主意,看看散列会是什么样子:)

于 2013-10-27T15:37:04.903 回答