3

我目前正在一个大型应用程序中从 rails 2 迁移到 rails 3。在我们的功能规范中,我们有很多这样的东西:

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

...

@child.should_receive(:method).twice

主要问题是,如果我让它命中 DB 并获得子的实际实例,真实的 :method 会使测试过于复杂(需要两个大工厂)并且速度很慢。

在代码中,我们使用各种方法来获取项目:查找、动态查找器等

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

您如何建议将此逻辑移至 Rails 3?对另一个存根/模拟库有什么建议吗?

4

1 回答 1

10

通常你会在控制器规范中模拟模型:

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

但是,当您进入gem "rspec-rails", "~> 2.0"rails 3 应用程序的 Gemfile 时,标准 rails 脚手架生成器将使用 rspec 为您生成规范,因此运行rails generate scaffold MyResource将为您生成一些示例规范。

以下是 rails/rspec 将为控制器规范生成的内容的轻度注释版本,因此我认为这应该被视为“RSpec 方式”。

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
于 2011-06-15T22:20:45.763 回答