Rspec 2 and Rails 3: stubbing / mocking

I am currently moving on to rails 3 from rails 2 in a large application. In our functional specifications, we have many such things:

@model = Factory :model
@child = Factory :child
Model.stub!(:find).and_return(@model)
Child.stub!(:find).and_return(@child)

...

@child.should_receive(:method).twice

The main problem is that if I let her delete the DB and get the actual instance of child, real: the method makes the tests too complicated (two large factories are needed) and slow.

In the code, we use various ways to get elements: find, dynamic finders, etc.

@model = Model.find(1)    
@child = @model.children.find_by_name(name)

How would you recommend moving this logic to rails 3? Maybe some advice on another tier / mock library?

+3
source share
1 answer

Usually you mock the model inside the controller specification:

Model.stub!(:find).and_return(mock_model('Model'))
Child.stub!(:find).and_return(mock_model('Child'))

, gem "rspec-rails", "~> 2.0" rails 3 app Gemfile, rails rspec , rails generate scaffold MyResource .

, rails/rspec , , "RSpec Way".

describe AccountsController do

  # Helper method that returns a mocked version of the account model.
  def mock_account(stubs={})
    (@mock_account ||= mock_model(Account).as_null_object).tap do |account|
      account.stub(stubs) unless stubs.empty?
    end
  end

  describe "GET index" do
    it "assigns all accounts as @accounts" do
      # Pass a block to stub to specify the return value
      Account.stub(:all) { [mock_account] }
      get :index
      # Assertions are also made against the mock
      assigns(:accounts).should eq([mock_account])
    end
  end

  describe "GET show" do
    it "assigns the requested account as @account" do
      Account.stub(:find).with("37") { mock_account }
      get :show, :id => "37"
      assigns(:account).should be(mock_account)
    end
  end

  describe "GET new" do
    it "assigns a new account as @account" do
      Account.stub(:new) { mock_account }
      get :new
      assigns(:account).should be(mock_account)
    end
  end
end
+10

All Articles