Reputation: 38359
Trying something simple and overlooking the obvious I'm sure. Shouldn't Factory_Girl be automatically creating the association? If so why does "GET index" spec below fail because event_id
is nil?
Event has_many :posts
#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
Edit: Additional spec example:
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
Upvotes: 0
Views: 919
Reputation: 11647
From the FactoryGirl wiki: https://github.com/thoughtbot/factory_girl/wiki/Usage
# Attribute hash (ignores associations) user_attributes = Factory.attributes_for(:user)
So you are not getting an event_id, and that's why it's failing.
Also, you said you tried post = FactoryGirl.create(:post)
but you should do post = Factory.create(:post)
and that will get it to work.
Perhaps in your before() block you should just create and save the post, unless you have a test that requires it to not be saved yet.
Upvotes: 1
Reputation: 309
Try changing
validates_presence_of :event_id
to
validates_presence_of :event
Upvotes: 0