【问题标题】:Testing has_many with shoulda-matchers using rspec3使用 rspec3 使用 shoulda-matchers 测试 has_many
【发布时间】:2014-10-02 18:09:03
【问题描述】:

我第一次尝试在新应用中使用 rspec3。我定义了两个简单的模型:

class Match < ActiveRecord::Base
end

class Article < ActiveRecord::Base
  has_many :matches
end

当我从控制台访问这些模型时,我可以创建关联并将它们按预期存储在数据库中。但是,当我尝试运行规范来测试它时,它似乎不起作用:

require 'spec_helper'

describe Article do
   it { is_expected.to have_many(:matches) }
   # it { should have_many(:matches) }
end

我尝试同时运行isexpected 版本和should 版本的测试,但在这两种情况下,我都会收到以下错误:

> ./bin/rspec spec/models/article_spec.rb
Warning: Running `gem pristine --all` to regenerate your installed gemspecs (and deleting then reinstalling your bundle if you use bundle --path) will improve the startup performance of Spring.
F

Failures:

  1) Article should have many :matches
     Failure/Error: it { is_expected.to have_many :matches }
       expected #<Article:0x007fa14c276f38> to respond to `has_many?`
     # ./spec/models/article_spec.rb:4:in `block (2 levels) in <top (required)>'
     # -e:1:in `<main>'

Finished in 0.09484 seconds (files took 0.63853 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/models/article_spec.rb:4 # Article should have many :matches

Randomized with seed 24636

以下是 Gemfile.lock 中的相关依赖:

rspec-core (3.0.4)
  rspec-support (~> 3.0.0)
rspec-expectations (3.0.4)
  rspec-support (~> 3.0.0)
rspec-mocks (3.0.4)
  rspec-support (~> 3.0.0)
rspec-rails (3.0.2)
  rspec-core (~> 3.0.0)
  rspec-expectations (~> 3.0.0)
  rspec-mocks (~> 3.0.0)
  rspec-support (~> 3.0.0)
rspec-support (3.0.4)
spring-commands-rspec (1.0.2)
rspec-rails (~> 3.0.0)
spring-commands-rspec
...
  shoulda-matchers (2.7.0)
shoulda-matchers

看起来应该很直截了当。我是否做错了什么导致我收到此错误?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec shoulda rspec3


    【解决方案1】:

    这是由于运行了安装 Spring 时创建的 binstub:

    ./bin/rspec spec/models/article_spec.rb
    

    显然这与运行 RSpec 安装的可执行文件的方式不太一样,这很简单:

    rspec spec/models/article_spec.rb
    

    【讨论】:

    • 有趣的想法,但不幸的是,当我这样做时,我得到了同样的错误。还值得注意的是,使用 rspec2,我无需明确定义主题即可以这种方式使用关联匹配器。
    • 哎呀,你说得对,我忘记了 shoulda-matchers 是如何工作的。我会删除这个回复,但是你能添加 Rails 和 RSpec 的版本吗?我有你的代码在 Rails 4.1.5 和 RSpec 3.1.5 上工作
    • 错误和 rspec 版本都在我原来的问题中。 rails 版本是 4.1.4。
    • 啊哈。试试rspec 而不是./bin/rspec
    • 哇,就是这样。我使用 spring 存根生成器自动生成 bin/rspec,让 rspec 运行通过 spring。所以,现在的问题是当我使用 bin 脚本时发生了什么不同。如果你更新你的答案,我会继续接受它。
    【解决方案2】:

    我不确定根本原因是什么,但我遇到了同样的问题 - bin/rspec 和 rspec。 我设法让它适用于 rspec,但不适用于 bin/rspec。

    我必须将 require 'shoulda/matchers' 添加到规范文件以及 rails_helper.rb 以使测试通过。这通过了一次,之后我可以从规范文件中删除它并且测试通过了。奇怪且不令人满意的修复。

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      相关资源
      最近更新 更多