Naveena
Naveena

Reputation: 53

How to include methods of models in RSpec test cases

I'm writing some Rspec tests with capybara , and as part of that I need some methods of model.

I have created my model as:

class MyModel < ActiveRecord::Base
  def method_name
    #some stuff..
  end
end

Now, I want to use MyModel in my Rspec test cases.

I tried to includeconfig.include Models in spec_helper.rb but it throws error

Uninitialized constant Models

And when I tried to include

include MyModel.new.method_name()

it throws error `include': wrong argument type nil (expected Module) (TypeError)

Without including any model class it runs test cases, but then my test cases are useless.

Here is my Rspec test case

require 'spec_helper'
describe "State Agency Page" do
    let(:state_data) { FactoryGirl.build(:state_data) } 
    require 'mymodel.rb'
    before {visit state_modifier_path}

    it "should have breadcrumb", :js=>true do
        page.should have_css('.breadcrumb')
    end
end

Please provide any solution.

Thanks in advance.

Upvotes: 0

Views: 1811

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29379

I don't know what you mean by "your test cases are useless", but you seem to misunderstand the role of Ruby's include method.

With Rails, or the use of the rspec-rails gem with RSpec, your classes will be autoloaded when you reference the corresponding class constant (e.g. MyModel). So there generally is no need to do manual "loading" of individual models. Just make sure you have require 'spec_helper' at the beginning of your specs.

As for the errors you were getting with your attempts to use include, I suggest you find and read a Ruby reference to understand the semantics of the include method and why each attempt of yours failed in the way it did.

Upvotes: 1

Related Questions