Skip to content

Instantly share code, notes, and snippets.

@link82
Created April 11, 2013 21:09
Show Gist options
  • Save link82/5367186 to your computer and use it in GitHub Desktop.
Save link82/5367186 to your computer and use it in GitHub Desktop.
I'm playing with rspec and factory girl but I'm stuck with a validation error for duplicate device entries while testing even if it should create different apps and devices for every test
class Device < ActiveRecord::Base
attr_accessible :app_id, :app_version, :locale, :push_token, :uid, :alias
belongs_to :app
validates_presence_of :app
validates :push_token,
:presence => true, :uniqueness => {:scope => :app_id, :message => 'already registered'}
validates_presence_of :locale
end
FactoryGirl.define do
factory :app do
environment 'production'
sequence(:name){|n| "Test#{n}Application"}
os 'iOS'
version '1.0'
sequence(:bundle_identifier){|n| "com.getting_angry.Test#{n}Application"}
certificate_expire_at nil
app_administrator 'Adokdsas@gmail.com'
#created 10 devices
after(:create) do |app, evaluator|
FactoryGirl.create_list(:device, 8, app: app)
FactoryGirl.build_list(:en_US_device, 2, app: app)
end
factory :app_with_notifications do
ignore do
notifications_count 5 #default nr
end
after(:create) do |app, evaluator|
FactoryGirl.create_list(:notification, evaluator.notifications_count, app: app)
end
end
factory :app_with_broadcast_notifications do
ignore do
notifications_count 10 #default nr
end
after(:create) do |app, evaluator|
FactoryGirl.create_list(:broadcast_notification, evaluator.notifications_count, app: app)
end
end
end
end
FactoryGirl.define do
factory :device do |d|
d.app_version '1.0'
d.locale 'it_IT'
d.sequence(:push_token){|p| 'raad0saadw0wdi0ae9a#{p}'}
d.uid 'test_user'
d.association :app, factory: :app
factory :en_US_device do |e|
e.locale 'en_US'
end
end
end
require "spec_helper"
describe App do
it "should limit notifications sent" do
a = FactoryGirl.create(:app_with_notifications,notifications_count: 80)
a.notifications.length.should == 80
a.should_receive(:send_notifications).exactly(2).times
a.check_notifications(true)
end
it "should generate 'broadcast' notifications" do
a = FactoryGirl.create(:app_with_broadcast_notifications, notifications_count: 1)
a.notifications.length.should == 1
data = a.explode_notification(a.notifications.first)
data.length.should == a.devices.count
end
end
@harlow
Copy link

harlow commented Apr 12, 2013

Couple of other ideas:

Future-proof your app and use strong_parameters over attr_accessible:

https://github.com/rails/strong_parameters

Use the FactoryGirl shorthand syntax methods:

# spec/spec_helper.rb
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

app = create(:app_with_notifications, notifications_count: 80)

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