Skip to content

Instantly share code, notes, and snippets.

@monfresh
Last active December 18, 2015 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monfresh/5816579 to your computer and use it in GitHub Desktop.
Save monfresh/5816579 to your computer and use it in GitHub Desktop.
Rails controller create action for Mongoid embedded_in model. What is the right way to test the post :create action in this situation?
# app/models/user.rb
class User
include Mongoid::Document
embeds_many :api_applications
...
end
# app/models/api_application.rb
class ApiApplication
include Mongoid::Document
field :name, :type => String
field :main_url, :type => String
field :callback_url, :type => String
embedded_in :user
...
end
# app/controllers/api_applications_controller.rb
class ApiApplicationsController < ApplicationController
before_filter :authenticate_user!
...
def create
@api_application = current_user.api_applications.new(params[:api_application])
respond_to do |format|
if @api_application.save
format.html { redirect_to @api_application, notice: 'Your application was successfully created.' }
else
format.html { render action: "new" }
end
end
end
...
end
# spec/controllers/api_applications_controller_spec.rb
require 'spec_helper'
describe ApiApplicationsController do
before (:each) do
@user = FactoryGirl.create(:user)
sign_in @user
end
let(:valid_attributes) { { name: "test app",
main_url: "http://localhost:8080",
callback_url: "http://localhost:8080" } }
...
describe "POST create" do
describe "with valid params" do
it "creates a new ApiApplication" do
expect {
post :create, { :api_application => valid_attributes }
}.to change(@user.api_applications, :count).by(1)
end
end
end
end
# spec/factories/users.rb
FactoryGirl.define do
factory :user do
name 'Test User'
email 'example@example.com'
password 'mong01dtest'
password_confirmation 'mong01dtest'
confirmed_at Time.now
end
end
# The spec fails with this error:
# Failure/Error: expect {
# count should have been changed by 1, but was changed by 0
# How can I test the post :create action in this situation?
@monfresh
Copy link
Author

The answer is to use reload because counts are cached.

expect {
  post :create, { :api_application => valid_attributes }
}.to change { @user.reload.api_applications.count }.by(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment