通过Factory_girl进行的关联失败的RSpec验证

时间:2011-08-11 16:53:24

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

尝试简单的事情并忽略明显的我确定。 Factory_Girl不应该自动创建关联吗?如果是这样,为什么“GET index”规范失败,因为event_id nil

活动has_many:帖子

#post.rb
  ...
  belongs_to :event
  validates :event_id, :presence => true
  ...

#factories.rb
Factory.define :event do |event|
  event.name "The Long Event Title"
end

Factory.define :post do |post|
  post.title "This is a post"
  post.association :event
end


#posts_controller_spec.rb
before(:each) do
  @attr = Factory.attributes_for(:post)
end

describe "GET index" do
  it "assigns all posts as @posts" do
    post = @user.posts.create(@attr)    ### <-- event_id not assigned?
    # post = FactoryGirl.create(:post)  ### <-- this doesn't work either
    get :index
    assigns(:posts).should eq([post])
  end
end

修改:其他规范示例:

describe "POST create" do
    describe "with valid params" do
      it "creates a new Post" do
        expect {
          post :create, :post => @attr, :event => Factory.create(:event)  <- fail
        }.to change(Post, :count).by(1)
      end

2 个答案:

答案 0 :(得分:1)

来自FactoryGirl wiki:https://github.com/thoughtbot/factory_girl/wiki/Usage

# Attribute hash (ignores associations)
user_attributes = Factory.attributes_for(:user)

所以你没有得到event_id,这就是它失败的原因。

此外,您说过您尝试了post = FactoryGirl.create(:post),但您应该post = Factory.create(:post),这样才能让它发挥作用。

也许在你的before()块中你应该创建并保存帖子,除非你有一个测试要求它还没有保存。

答案 1 :(得分:0)

尝试更改

validates_presence_of :event_id

validates_presence_of :event
相关问题