Search code examples
ruby-on-railsruby-on-rails-3rspecfactory-botrspec-rails

Very simple Rspec rails test is not passing, where it should


I'm having some problems creating an rspec test to my rails application.

Let say that I have a model called MyModel, with the following function, that obtains the instances of all the MyModels that have an empty text

self.searchEmtpy:
  self.where(:text => nil)
end

I've defined the following test, that checks that, new MyModels with empty text, should be returned by the previous function. I use FactoryGirl for the model creation.

describe "get empty models" do
  before do
    @previousModels=MyModel.searchEmtpy
    @newModel=Factory(:myModel, :text => nil)
  end
  it "new empty models should appear" do
    currentModels=MyModel.searchEmtpy
    (previousModels << @newModel).should eq(currentModels)
  end
end

The test is quite simple, but its not working. I don't know why, but, for what I understand from the output, it seams that, on the "should" line, previousModels already contains the newModel on it, so the test fails (it contains @newModel 2 times. I'm missing something obvious? Aren't the instructions inside "it" called in order?

To clarify, the following test does not fail, where it should:

describe "get empty models" do
  before do
    @previousModels=MyModel.searchEmtpy
    @newModel=Factory(:myModel, :text => nil)
  end
  it "new empty models should appear" do
    currentModels=MyModel.searchEmtpy
    (previousModels).should eq(currentModels)
  end
end

Solution

  •  self.where(:text => nil)
    

    Is an ActiveRecord::Relation - the query doesn't actually fire until you try to do something to it (like iterate over it, append to it etc.)

    In this case that happens on the same line as your call to should, ie after the factory has created the instance.

    One way to fix this would be to force the evaluation of the relation in your before block, for example call .all on it.