Testing "Post create" with Rspec
Asked Answered
P

2

6

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?

Potful answered 11/5, 2012 at 11:46 Comment(0)
L
5

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

Lenticular answered 11/5, 2012 at 13:18 Comment(0)
T
3

As the guide points out:

# Returns a hash of attributes that can be used to build a User instance
attrs = FactoryGirl.attributes_for(:user)
Threesquare answered 22/11, 2013 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.