Here is my controller test:
test "should get create" do
sign_in(FactoryGirl.create(:user, admin: true))
assert_difference('Event.count') do
post :create, FactoryGirl.build(:event)
end
assert_not_nil assigns(:event)
assert_response :success
end
and when I add the simplest validation to events.rb
class Event < ActiveRecord::Base
attr_accessible :city, :date, :name, :state, :street
has_many :periods
validates :name, presence: true
end
I get:
1) Failure:
test_should_get_create(EventsControllerTest) [/Users/noahc/Dropbox/mavens/test/functional/events_controller_test.rb:37]:
"Event.count" didn't change by 1.
<2> expected but was
<1>.
But, then I look at events_factory.rb
factory :event do
name 'First Event'
street '123 street'
city 'Chicago'
state 'IL'
date Date.today
end
And there doesn’t seem to be an issue with name being required.
update:
When I make my test:
test "should get create" do
sign_in(FactoryGirl.create(:user, admin: true))
assert_not_nil assigns(:event)
assert_response :success
end
I get:
1) Failure:
test_should_get_create(EventsControllerTest) [/Users/noahc/Dropbox/mavens/test/functional/events_controller_test.rb:38]:
<nil> expected to not be nil.
When I remove that line, and leave in the assert_response :success it passes.
update 2:
def create
@event = Event.new(params[:event])
@event.save
end
What about changing this:
to:
Explanation:
postexpects a hash with the attributes of the record you’re creating.FactoryGirl.build(:event)creates a new unsaved instance of the model (event), which is not what you want. Since you had no validations on your model, this was somehow getting by and being ignored, so in fact the factory was having no influence on the newly-created event (which I assume was being created with blank attributes).attributes_for, in contrast, returns the attributes of the factory as a hash, so:which is exactly what you want. When you pass this to
post, it assigns the attributes from the hash toparams, which are then used to create a new event in the line:Event.new(params[:event]).