2

我第一次尝试在新应用中使用 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

看起来它应该很简单。我是否做错了什么导致我收到此错误?

4

2 回答 2

2

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

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

显然,这与运行 RSpec 安装的可执行文件的工作方式不同,这很简单:

rspec spec/models/article_spec.rb
于 2014-10-02T18:57:38.833 回答
0

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

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

于 2015-03-03T20:35:09.893 回答