我设置工厂女孩的方式有问题

时间:2013-01-22 18:01:00

标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot

我正在关注micheal hartl rails教程。我在第10章。我在工厂女孩中定义强效部分的方式有问题。 当我打电话给rspec时,我从工厂女孩那里得到了这个错误。

Failure/Error: FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
     NoMethodError:
       undefined method `content=' for #<User:0x0000010343f018>

factories.rb

FactoryGirl.define do
  factory :user do
    sequence(:name)    { |n| "Person #{n}" }
    sequence(:email)   { |n| "person_#{n}@example.com" }
    password "foobar"
    password_confirmation "foobar"

    factory :admin do
      admin true
    end

    factory :micropost do 
       content "Lorem ipsum "
       #association :user
       user
    end
  end 
end

被称为

的部分
 before { @user.save }
    let!(:older_micropost ) do 
      FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
    end
    let!(:newer_micropost) do
      FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago)
    end
    it " should  have  the right  micropost in the right  order" do 
      @user.microposts.should == [newer_micropost, older_micropost]
    end

1 个答案:

答案 0 :(得分:1)

factory :micropost获取factory :user,否则会将content视为用户的属性。

这应该有效:

FactoryGirl.define do
  factory :user do
    sequence(:name)    { |n| "Person #{n}" }
    sequence(:email)   { |n| "person_#{n}@example.com" }
    password "foobar"
    password_confirmation "foobar"

    factory :admin do
      admin true
    end
  end 

  factory :micropost do 
    content "Lorem ipsum "
    association :user
  end

end