Post request in controller specs - ruby-on-rails

I have problem with testing my controller. I've test post request in 2 context. With valid attributes and with invalid attributes. I have problem with valid attributes context.
I have the following test:
describe "POST #create" do
context "with valid attributes" do
it "saves the new car_configuration in the database" do
expect{
post :create, car_configuration: attributes_for(:car_configuration)
}.to change(CarConfiguration, :count).by(1)
end
it "redirects to the index car_configuration" do
post :create, car_configuration: attributes_for(:car_configuration)
should redirect_to admin_car_configurations_url
end
end
end
And my car_configuration factory is:
FactoryGirl.define do
factory :car_configuration do
sequence(:image) {|n| "Image #{n}"}
small_cases_count 5
big_cases_count 2
association :body_style, factory: :car_body_style
association :model, factory: :car_model
association :car_class
end
end
And errors that rspec shows:
1) Admin::CarConfigurationsController POST #create with valid attributes saves the new car_configuration in the database
Failure/Error: expect{
count should have been changed by 1, but was changed by 0
# ./spec/controllers/admin/car_configurations_controller_spec.rb:42:in `block (4 levels) in <top (required)>'
2) Admin::CarConfigurationsController POST #create with valid attributes redirects to the index car_configuration
Failure/Error: should redirect_to admin_car_configurations_url
Expected response to be a <redirect>, but was <200>
# ./spec/controllers/admin/car_configurations_controller_spec.rb:49:in `block (4 levels) in <top (required)>'

spec/controllers/admin/car_configuratoins_controller_spec.rb
require 'spec_helper'
describe Admin::CarConfigurationsController do
let(:configuration) { build :configuration }
context "POST create" do
it "creates a config" do
expect { perform }.to change(CarConfiguration, :count).by(1)
end
def perform
post :create, car_configuration: configuration.attributes
end
end
end

Related

Devise RSpec Error

I am trying to validate that the current_user's organization matches that of the organization they are trying to view.
Here's the part of the controller that's failing this test (#organization is being defined in an earlier method):
if current_user.organization != #organization
redirect_to root_path, notice: "Not authorized to edit this organization"
end
Here's the failing test:
require 'rails_helper'
RSpec.describe Admin::PagesController, :type => :controller do
describe 'GET #home' do
login_user
before do
#organization = FactoryGirl.create(:organization)
end
context "valid params" do
it "renders the home template and returns http 200" do
get :home, name: #organization.name
expect(response).to render_template("home")
expect(response.status).to eq(200)
end
end
end
Here's my factory:
factory :user do
email { Faker::Internet.email }
organization_id 1
password "foobarfoobar"
password_confirmation { |u| u.password }
end
...And here's where login_user is being defined:
module ControllerMacros
def login_user
#request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
sign_in user
end
end
Stacktrace:
1) Admin::PagesController GET #home valid params renders the home template and returns http 200
Failure/Error: it "renders the home template and returns http 200" do
expecting <"home"> but rendering with <[]>
# ./spec/controllers/admin/pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
However:
[2] pry(#<RSpec::ExampleGroups::AdminPagesController::GETHome::ValidParams>)> subject.current_user.organization == #organization
=> true
Not sure what is going wrong here, seems like pretty standard stuff. Any ideas?
Turns out the issue was that I was sending in the wrong parameter - should have been sending #organization.subdomain, not #organization.name. :(

Failing uniqueness validation with FactoryGirl

I'm having problems with FactoryGirl, I'm using sequence to avoid duplicating fields, but validations are failing anyway.
Output:
1) CustomersController anonymous user GET #edit is redirected to signin when accessing edit form
Failure/Error: get :edit, id: create(:customer)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/controllers/customers_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
3) Customer public class methods executes its methods correctly #find_by_id_or_name finds customer by name
Failure/Error: let(:john) {create(:customer, name: 'John Doe X')}
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/models/customer_spec.rb:25:in `block (3 levels) in <top (required)>'
# ./spec/models/customer_spec.rb:38:in `block (5 levels) in <top (required)>'
# -e:1:in `<main>'
Factories:
FactoryGirl.define do
factory :customer do
user
name {Faker::Name.name}
sequence(:mail) { |n| "person#{n}#example.com" }
address {Faker::Address.street_address}
phone {Faker::PhoneNumber.phone_number}
end
end
FactoryGirl.define do
factory :user do
sequence(:email) {|i| "example#{i}#example.com"}
password {Faker::Internet.password(10)}
end
end
These are the tests that are failing:
RSpec.describe Customer, type: :model do
describe "public class methods" do
let(:john) {create(:customer, name: 'John Doe X')}
let(:frank) {create(:customer)}
context "responds to its methods" do
it "responds to #find_by_id_or_name" do
expect(Customer).to respond_to(:find_by_id_or_name)
end
end
context "executes its methods correctly" do
context "#find_by_id_or_name" do
it "finds customer by name" do
customer = Customer.find_by_id_or_name('John Doe X')
expect(customer).to eq john
end
it "finds customer by id" do
customer = Customer.find_by_id_or_name(frank.id)
expect(customer).to eq frank
end
end
end
end
end
RSpec.describe CustomersController, type: :controller do
context "signed in user" do
before :each do
#user = create(:user)
end
describe "GET #edit" do
it "renders :edit view" do
get :edit, id: create(:customer).id
expect(response).to render_template(:edit)
end
end
describe "DELETE #destroy" do
before :each do
#customer = create(:customer, user: #user)
end
it "deletes record" do
expect {delete :destroy, id: #customer.id}.to change(Customer, :count).by(-1)
end
end
end
end
This is happening to me all over my app. I just copied some tests that apply to Customer.
Thanks
My problem was related to not appropiately configuring database_cleaner. The configuration in this post solves the problem: How can I clean my database between erroneous rspec specs?

FactoryGirl::InvalidFactoryError Controller Spec

I'm trying to create a controller spec for a contact form. All I want is to test that the :new template is rendered when invalid attributes are submitted. I've tried various configurations of the factory, as well as changing it to a trait, instead of factory to no avail. The error message doesn't get very specific, just Invalid Factory. Any ideas would be appreciated!
# blog_app/spec/factories/inquiries.rb
FactoryGirl.define do
factory :inquiry do
name "TestName"
email "test#test.com"
phone "123-456-7890"
message "TestMessage"
end
factory :invalid_inquiry, parent: :inquiry do
name nil
end
end
#/app/controllers/inquiries_controller.rb
class InquiriesController < ApplicationController
def new
#inquiry = Inquiry.new
end
def create
#inquiry = Inquiry.new(params[:inquiry])
if #inquiry.deliver
render :thank_you
else
render :new
end
end
end
# spec/controllers/inquiries_controller_spec.rb
require 'spec_helper'
describe InquiriesController do
it "has a valid factory" do
FactoryGirl.build(:inquiry).should be_valid
end
describe "POST #create" do
context "with valid attributes" do
it "delivers inquiry" #pending
it "renders the :thank_you page template" do
post :create, inquiry: FactoryGirl.attributes_for(:inquiry)
response.should render_template :thank_you
end
end
context "with invalid attributes" do
it "does not deliver inquiry" do #pending
it "renders :new page template" do
post :create, inquiry: FactoryGirl.attributes_for(:invalid_inquiry)
response.should render_template :new
end
end
end
describe "GET #new" do
it "renders :new page template" do
get :new
response.should render_template :new
end
end
end
Finished in 0.31244 seconds
0 examples, 0 failures
/Users/.../.rvm/gems/ruby-2.0.0-p353/gems/factory_girl-4.4.0/lib/factory_girl.rb:73:in `lint': The following factories are invalid: (FactoryGirl::InvalidFactoryError)
* invalid_inquiry
from /Users/.../Documents/blog_app/spec/support/factory_girl.rb:8:in `block (2 levels) in <top (required)>'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:21:in `instance_eval'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:21:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `block in run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `each'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:66:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:418:in `run_hook'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:27:in `block in run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/reporter.rb:34:in `report'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:25:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
from /Users/.../.rvm/gems/ruby-2.0.0-p353/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'
Does this work?
FactoryGirl.define do
factory :inquiry do
name "TestName"
email "test#test.com"
phone "123-456-7890"
message "TestMessage"
factory :invalid_inquiry do
name nil
end
end
end
Alternatively you might try replacing:
post :create, inquiry: FactoryGirl.attributes_for(:invalid_inquiry)
with:
post :create, inquiry: FactoryGirl.attributes_for(:inquiry, name: nil)
and getting rid of the invalid_inquiry factory altogether.

FactoryGirl.attributes_for(:item) not passing on POST #create

I try to pass these two create controller specs but for some reason it it not validating the Item object. Could it be that FactoryGirl.attributes_for(:item) are missing the profile and attachment required associations? If so, how can I pass it to attributes too?
describe "POST #create" do
context "signed in" do
login_user
context "with valid attributes" do
it "creates a new item" do
expect{
post :create, trend: FactoryGirl.attributes_for(:item)
}.to change(Item,:count).by(1)
end
it "redirects to the home page" do
post :create, item: FactoryGirl.attributes_for(:item)
response.should redirect_to Item.last
end
end
end
I got these errors
Failures:
1) ItemsController POST #create signed in with valid attributes creates a new item
Failure/Error: expect{
count should have been changed by 1, but was changed by 0
# ./spec/controllers/items_controller_spec.rb:42:in `block (5 levels) in <top (required)>'
2) ItemsController POST #create signed in with valid attributes redirects to the home page
Failure/Error: response.should redirect_to Item.last
Expected response to be a <redirect>, but was <200>
# ./spec/controllers/items_controller_spec.rb:48:in `block (5 levels) in <top (required)>'
This is the Item factory
FactoryGirl.define do
factory :item do
profile
after(:build) do |item|
item.attachments << FactoryGirl.build(:attachment, attachable: item)
end
end
end
I guess doing FactoryGirl.attributes_for isn't actually a build, so the after(:build) won't fire. How about this:
FactoryGirl.attributes_for(:item, :profile_attributes => FactoryGirl.attributes_for(:profile), :attachments => [FactoryGirl.attributes_for(:subject)])
Probably a good idea to try this line in the rails console first to see what the hash comes out like :)

RSpec + FactoryGirl should_receive failing

I can't figure out why this RSpec test fails. Any advice? I'm new-ish to FactoryGirl, RSpec, and TDD in general.
Controller:
def update
#vendor = current_user.vendors.find(params[:id])
if #vendor.update_attributes(params[:vendor])
redirect_to vendor_path(#vendor)
else
render 'edit'
end
end
Test:
require 'spec_helper'
describe VendorsController do
login_user
before :each do
#user = subject.current_user
#vendor = FactoryGirl.create(:vendor, :user => #user)
end
[...]
describe 'POST update' do
def do_update
post :update, :id => #vendor.id, :vendor => FactoryGirl.attributes_for(:vendor)
end
[...]
it 'should update a given vendor' do
do_update
#vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
end
end
end
Factory:
FactoryGirl.define do
factory :vendor do
name 'Widget Vendor'
user
end
end
The Failure:
Failures:
1) VendorsController POST update should update a given vendor
Failure/Error: #vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
(#<Vendor:0x007faeb75e77d0>).update_attributes({:name=>"Widget Vendor"})
expected: 1 time
received: 0 times
# ./spec/controllers/vendors_controller_spec.rb:108:in `block (3 levels) in <top (required)>'
Update:
I'm a little closer, now. I changed the test to the following:
it 'should update a given vendor' do
Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
do_update
end
And the new error is:
Failures:
1) VendorsController POST update should update a given vendor
Failure/Error: post :update, :id => #vendor.id, :vendor => FactoryGirl.attributes_for(:vendor)
#<Vendor:0x007ff30d765900> received :update_attributes with unexpected arguments
expected: ({:name=>"Widget Vendor"})
got: ({"name"=>"Widget Vendor"})
# ./app/controllers/vendors_controller.rb:33:in `update'
# ./spec/controllers/vendors_controller_spec.rb:98:in `do_update'
# ./spec/controllers/vendors_controller_spec.rb:108:in `block (3 levels) in <top (required)>'
Answer...?
Well, this worked. There has to be a better way of doing this, though:
Vendor.any_instance.should_receive(:update_attributes).with(JSON.parse(FactoryGirl.attributes_for(:vendor).to_json)).and_return(true)
I think you are doing it wrong.
The #vendor object in specs is another one that in your controller, so it doesn't receive "update_attributes" method.
You can try this (rspec 2.5+ probably):
Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
Or you can check if object attributes has changed:
expect{
do_update
}.to change(...)
I believe you need to set your expectations before posting the request; otherwise, by the time it hits your expectation the object has already been set. So move do_update after your should_receive line:
it 'should update a given vendor' do
#vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
do_update
end
You can use the Hash stringify keys method in rails:
Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor).stringify_keys)

Resources