user225643
user225643

Reputation: 3701

Requiring devise in rspec model spec

I'm using devise in my Admin model like so:

class Admin < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

Functionally, this is working fine. But I want to have specs for my Admin class, so I start to write a spec...

require 'spec_helper'
require 'admin'

describe Admin do
  it 'mumblemumble' do ... end
end

...and then when I go to run the spec, it blows up:

active_record/dynamic_matchers.rb:22:in `method_missing': undefined method `devise' for Admin(Table doesn't exist):Class (NoMethodError)

How do I require Devise so that it's available in my spec? It seems like I should be able to

require 'devise'

in either my spec or my model (preferably my model), but this doesn't fix the issue or change my stack trace. How do I require Devise so that my model has the helper method available? I'm poking around the Devise gem but I'm not finding any clues.

Upvotes: 0

Views: 517

Answers (4)

user225643
user225643

Reputation: 3701

Got it. I run specs with an in-memory instance of sqlite3, so all the db:test:prepare doesn't apply to me. In addition to requiring Devise, it must also be setup/configured.

So in /spec/support/devise.rb:

require 'devise'

Devise.setup do |config|
  require 'devise/orm/active_record'
end

And then in spec_helper.rb:

Dir["./spec/support/**/*.rb"].sort.each {|f| require f}

Upvotes: 0

Yann Marquet
Yann Marquet

Reputation: 69

Yes it seems your test database does not have the admins table. Try this:

bundle exec rake db:migrate db:test:prepare

db:migrate migrates your development database, if there are any pending migrations and db:test:prepare clones your test database according to the development one.

Upvotes: 1

Bruce Lin
Bruce Lin

Reputation: 2740

This error

undefined method `devise' for Admin(Table doesn't exist):Class (NoMethodError)

seems to be that you don't have the table in the db? Did you migrate the rake file?

Upvotes: 1

Nick Veys
Nick Veys

Reputation: 23949

How are you running these? RSpec directly? Or bundle exec rake spec?

There's this in your error: for Admin(Table doesn't exist) which makes me wonder if you have a database yet. The rake task should take care of setting up your world for you.

If that doesn't help, post your spec_helper.rb contents too.

Here's a basic Admin model I have:

class Admin < ActiveRecord::Base
  devise :database_authenticatable, :recoverable, :rememberable,
         :trackable, :validatable
end

And a basic spec:

require 'spec_helper'

describe Admin do
  it { should validate_uniqueness_of(:email) }
end

Works great with vanilla generated rails app and generated devise setup.

Upvotes: 1

Related Questions