Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing "Post create" with Rspec

I am trying to test a "Post create" action with Rspec. The code is as follows:

   def valid_attributes
     {
    :zone => Flymgr::Zone.new(:countries => Flymgr::ZoneCountry.first,
        :name => 'USA',
        :description => 'USA Flight',
        :zipcodes => ''),
    :price => '100.00',
    :class => 'first',

     }
   end

   def valid_session
     {}
   end

   before(:each) do
       @request.env["devise.mapping"] = Devise.mappings[:admin]
       admin = FactoryGirl.create(:admin)
       sign_in admin                           
      end

describe "POST create" do
     describe "with valid params" do
       it "creates a new Flymgr::Rule" do
         expect {
           post :create, {:Flymgr_rule => valid_attributes}
         }.to change(Flymgr::Rule, :count).by(1)
       end

One of the required attributes for the form is a 'zone', this is a dropdown box and the options for the dropdown are created with a different form. I do not know how to create an form entry using Rspec. As you can see, I have tried to call a method from a different controller Flymgr::Zone.new. I don't think this is working and it is breaking my test.

Can anyone advise on the best way to do this? Perhaps I should be using FactoryGirl to create a zone and rule entry?

like image 436
user1152142 Avatar asked May 11 '12 11:05

user1152142


2 Answers

your request parameter hash has an object as value of :zone, when you post it will just be 'to_s'-ed, which is unlikely what you want.

In general the best practice is to use factory girl to build your objects and use the attributes_for strategy to parameterize its attributes for the post request: What is the proper way to test 'create' controller actions?

Your question is suggesting that the association is a belong_to so you just need to post an id. Be aware that at present, FactoryGirl does not create any attributes for the associations. If your factory definition for rule takes care of the zone association, you can use this workaround:

FactoryGirl.build(:flymgr_rule).attributes

to also include a zone_id but, then you need to exclude the unwanted params. ("id", "created_at", "updated_at", etc).

So you may be better off explicitly insert the params hash info for zone the way you see it in a valid post request.

Read this thread on factorygirl attributes and associations: https://github.com/thoughtbot/factory_girl/issues/359

like image 70
Viktor Trón Avatar answered Sep 19 '22 01:09

Viktor Trón


As the guide points out:

# Returns a hash of attributes that can be used to build a User instance
attrs = FactoryGirl.attributes_for(:user)
like image 44
phillbaker Avatar answered Sep 19 '22 01:09

phillbaker