Skip to content

sadaf2605/nested_attr

Repository files navigation

NestedAttr

A little plugin to help you testing your Active Admin formastic forms easily when you are using FactoryGirl.

Description

FactoryGirl does not provide nested attributes when we do ‘FactoryGirl.attributes_for(:factory_name)`but when we are testing controller in active admin formastic form, usually we will need those nested attributes, which we usually do by hard coding post request which is very tiring. So in this plugin we have tried to solve this problem. Using this plugin you can get nested attributes just like (active admin) formastic form from your factory.

You can read more details at “Usage with active admin” section

Usage

Install:

gem 'nested_attr'

Basic Usage

require 'nested_attr'
attr = NestedAttr.nested_attr_for(:post_factory) #  {
                                                 #    categories_ids: [1,2,3],   # f.inputs :categories
                                                 #    tags: [ {name: "tech"} ] # f.has_many :tags
                                                 #  }
post :create, user: attr

Usage with active admin

Suppose you have a blog and you have these factories:

FactoryGirl.define do
  factory :admin_user, :class => AdminUser do
    sequence(:email){|n| "email#{n}@example.com"}
    password "password"
    password_confirmation "password"
  end

  factory :post, class: Post do
    user 
    title "this is a title"
    body "this is a huge body"

    after :build do |p|
      p.categories << create(:category)
    end
  end

  factory :category, class: Category do
    sequence :name do |n|
      "category#{n}"
    end
  end    
end

You have active admin installed at your rails app. At the form of your active admin you have following:

ActiveAdmin.register Post do
  permit_params :post

    form do |f|
      f.inputs :title, :body
      f.inputs :categories

        f.has_many :tags do |t|
          t.input :name
        end

      f.actions
    end

  end

Now you want to test your controller using rspec. How? Very simple. Like this:

include Devise::TestHelpers

RSpec.describe Admin::PostsController, :type => :controller do
  before(:each) do
    @user = FactoryGirl.create(:admin_user)
    sign_in @user
  end

  describe "Create" do
    it "creates post" do
      expect{post :create, post: NestedAttr.nested_attr_for(:post, has_many=[:tags])}.to change{Post.count}.by(1)
    end
  end
end

This project rocks and uses MIT-LICENSE.

About

A helper plugin for testing rails application that is using Factory Girl and Formastic Forms (eg. Active Admin)

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published