[ rspec ] FactoryGirl controller test

configure FactoryGirl

/spec/rails_helper.rb

RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end

 

setup Factory for users

/spec/factories/users.rb

FactoryGirl.define do
factory :user do
first_name 'ThisIsFirstName'
last_name 'ThisIsLastName'
email { SecureRandom.hex + '@whatever.com' }
end
end

 

controller

app/controllers/my_controller.rb

class MyController < ActionController::Base

attr_writer :current_user

def create
@myObject= MyObject.new(params.permit(:content))
authorize myObject

return if myObject.save

render json: myObject.errors, status: :unprocessable_entity
end

end

 

controller spec

/spec/controllers/mymodule/whatever_controller_spec.rb

require 'rails_helper'

RSpec.describe MyModule::WhateverController, type: :controller do
let!(:current_user) do
create(:user)
end

let!(:myObject) do
create(:myObject)
end

before do
allow_any_instance_of(MyController)
.to receive(:current_user).and_return(current_user)
end

describe '#show' do
it 'returns myObject' do
get :show, id: myObject.id, format: :json # get/post/patch
expect(assigns(:myObject)).to eq(myObject)
end
end

describe '#create' do
let(:create_params) do
{
attr1: 'whatever params',
format: :json
}
end

context 'with valid params' do
it 'creates a new MyObject' do
expect do
post :create, create_params
end.to change(MyObject, :count).by(1)
end

it 'assigns a newly created MyObject as @myObject' do
post :create, create_params
expect(assigns(:myObject)).to be_a(MyObject)
end
end
end

end

We use assigns to get the instance variables created within a controller action (and assigned to the view)

expect(myObject.reload.content).to eq('whatever')

 

http request method

get/post/xhr

xhr example

xhr :post, :create, params: params

ref : https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s