4

在我的控制器规格中,我是否有效?对于一些路由测试,(基于 Ryan Bates nifty_scaffold)如下:-

it "create action should render new template when model is invalid" do
  Company.any_instance.stubs(:valid?).returns(false)
  post :create
  response.should render_template(:new)
end

当我单独测试控制器时,这很好。我的模型规格中也有以下内容

it "is valid with valid attributes" do
  @company.should be_valid
end

当单独测试时,这再次工作正常。如果我为模型和控制器运行规范,就会出现问题。模型测试总是失败为有效?方法已被淘汰。当控制器测试被拆除时,我有没有办法删除 any_instance 的存根。

我通过以相反的字母顺序运行测试来解决这个问题,以确保模型测试在控制器之前运行,但我真的不喜欢我的测试依赖于序列。

4

3 回答 3

4

您需要手动配置 RSpec。

Rspec.configure do |config|
  ...

  # == Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  # config.mock_with :rspec
end

另外,请记住 Rspec 提供了自己的方法来模拟对象。使用 RSpec API,否则您将无法从库抽象中受益。 http://rspec.info/documentation/mocks/message_expectations.html

于 2010-04-23T08:40:50.140 回答
3

我有同样的问题,但实际上没有使用Rspec但正常。Test::UnitActionController::TestCase

定义的期望在测试中保持活力。

有什么线索可以在测试之间重置我的期望吗?

  • 红宝石:1.9.2
  • 导轨:3.0.3
  • 摩卡:0.9.10

更新:我已经用unstubMocha 方法解决了这个问题:http: //mocha.rubyforge.org/classes/Mocha/ObjectMethods.html#M000009

于 2011-01-29T12:57:39.703 回答
1

您的 spec_helper 是否包含

Spec::Runner.configure do |config|
  config.mock_with :mocha
end

有了那个 rspec 应该在测试之间拆除模拟。

于 2010-04-23T08:36:44.393 回答