Question

I am new in using ruby on rails and rspec

I am getting this problem when i try to execute the rspec tests for Mymodel Controller.

Mymodel is working as expected when i access the page via the browser... But fails when i execute the rspec tests!

class MymodelController < ApplicationController
  def show
    @model = Mymodel.find(:first, :conditions => { :title => "Model-Title" } );
  end
end

Then my rspec tests look like

require 'spec_helper'

describe MymodelController do

  describe "GET 'show'" do
    it "assigns @model as Mymodel" do
      get 'show'
      expect(assigns(:model)).to be_a Mymodel
    end

    it "assigns model should have 'Model-Title' as title" do
      get 'show'
      expect(assigns(:model).title).to eq "Model-Title" 
    end

  end

end

Any clues ?

Thanks!

EDIT: Here are the Errors encountered:

Failures: 

1) MymodelsController GET 'show' assigns model should have 'Model-Title' as title 
Failure/Error: expect(assigns(:model).title).to eq("Model-Title") 
NoMethodError: undefined method title' for nil:NilClass  
#./spec/controllers/mymodels_controller_spec.rb:15:in block (3 levels) in <top (required)>' The 

The line 15 is expect(assigns(:model).title).to eq("Model-Title")

2) MymodelsController GET 'show' assigns @model as mymodel
 Failure/Error: expect(assigns(:model)).to be_a(Mymodel)
   expected nil to be a kind of Mymodel(id: integer, title: string, created_at: datetime, updated_at: datetime)
 # ./spec/controllers/mymodels_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

The code line corrsponding is : expect(assigns(:model)).to be_a(Mymodel)

Was it helpful?

Solution

You haven't created any Mymodel instances in your test, so presumably the Mymodel.find is returning nil, which explains the errors you've shown in your edit (for the first example) and your comment (for the second example).

The NameError you've shown in your title and in your question body is most likely from an attempt to use assigns(model), which would failed in that fashion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top