jgpawletko
jgpawletko

Reputation: 512

Testing ActiveRecord associations with Shoulda in non-Rails app

App: Sinatra + ActiveRecord
Trying to test association existence using best practices.
I really like the Shoulda syntax:

    describe Bar do
      it { should belong_to(:foo) }
    end

However, RSpec cannot seem to find the belong_to method.

    1) ResOutcome 
       Failure/Error: it { should belong_to(:foo) }
       NoMethodError:
         undefined method `belong_to' for #<RSpec::Core::ExampleGroup::Nested_1:0x00000103ac6760>
       # ./spec/models/bar_spec.rb:48:in `block (2 levels) in <top (required)>'

Any hints?
Does Shoulda association testing only work in Rails apps (with rspec-rails)?
Thank you all for your time.

Upvotes: 2

Views: 1165

Answers (4)

LouieGeetoo
LouieGeetoo

Reputation: 868

As other answers mention, this happens because shoulda-matchers is being included before your ActiveRecord connection is established, at least on Sinatra.

In your Gemfile, be sure to add require: false, like so:

gem "shoulda-matchers", "~> 2.4.0", require: false

This prevents the app from automatically requiring the gem before anything else has been done.

Then in your spec/spec_helper.rb, first require your app (where active_record is presumably included and the connection is established), and then later in the file, manually require shoulda-matchers. For example:

require File.dirname(__FILE__) + '/../the_app_itself'
require 'shoulda-matchers'

Now you can use the matchers in your specs as usual:

describe LouieGeetoo do
  it { should have_many(:video_games) }
end

Yay!

Upvotes: 0

Steven Harlow
Steven Harlow

Reputation: 651

We had a similar problem and were working in a non-Rails app.

Our issue turned out to be because we had tried to require 'shoulda-matchers' before we had actually required our app, which meant that the gem was looking for ActiveRecord::Base and couldn't find it.

We fixed the problem by requiring the app first and then requiring 'shoulda-matchers' afterwards. Stupid.

Upvotes: 0

luacassus
luacassus

Reputation: 6720

Did you add shoulda-matchers gem to your Gemfile? https://github.com/thoughtbot/shoulda-matchers


Update:

Add require 'shoulda/matchers to your spec_helper.rb configuration.

Upvotes: 2

David van Geest
David van Geest

Reputation: 1997

I had a similar problem, although I'm not using RSpec. Still using Sinatra and ActiveRecord though.

In my case, I needed to change my test classes from inheriting from ActiveSupport::TestCase to inheriting from Test::Unit::TestCase.

I wasn't using the ActiveSupport::TestCase functionality anyway, so it worked OK. I realize this isn't really your use case, but maybe it points you in the right direction and helps someone else who is using Test::Unit.

Upvotes: 0

Related Questions