RSpec update_attributes期望失败,即使更新有效

时间:2013-11-13 00:44:15

标签: rspec expectations

我正在使用主要是脚手架生成的RSpec规范,这是失败但不应该。这是规范:

describe "PUT update" do
    describe "with valid params" do
      it "updates the requested invoice" do


      invoice = Invoice.create!

       Invoice.any_instance.should_receive(:update_attributes).with({"number" => "MyString"  })
    put :update, {:id => invoice.id, :invoice => { "number" => "MyString" }}
  end

运行规范时,会在数据库中创建一个发票,并进行适当更新。但是,我收到此消息并失败:

RSpec::Mocks::MockExpectationError: (#<Mocha::ClassMethods::AnyInstance:0x653a9a8>).update_attributes({"number"=>"MyString"})
expected: 1 time with arguments: ({"number"=>"MyString"})
received: 0 times with arguments: ({"number"=>"MyString"})

为什么会失败?

3 个答案:

答案 0 :(得分:1)

冒着明显的风险,因为你得到了Mocha错误,在我看来你需要禁用Mocha或配置它以用于RSpec。

您可以通过从Gemfile中删除gem并重新执行bundle install来禁用它。或者,您可以在指定gem时添加'require:false`参数,以便它不会自动加载,每Bundler: What does :require => false in a Gemfile mean?

配置Mocha以使用RSpec的说明在https://relishapp.com/rspec/rspec-core/v/2-14/docs/mock-framework-integration/mock-with-mocha

答案 1 :(得分:0)

我有类似的问题,我通过使用expect而不是should_receive来解决它。您可能只需要将其更新为使用期望,如下所示。


describe "PUT update" do
  describe "with valid params" do
    it "updates the requested invoice" do
      invoice = Invoice.create!
      Invoice.any_instance.expects(:update_attributes).with({"number" => "MyString"  })
      put :update, {:id => invoice.id, :invoice => { "number" => "MyString" }}
    end
  end
end

答案 2 :(得分:-1)

与许多其他模拟框架一样,Mocha要求您在运行测试代码之前提出您的期望。

因此,在你的测试中,交换两行;即在 Invoice.create!之后致电Invoice.any_instance.should_receive