ruby-on-rails - 使用 rspec3 测试 has_many 和 shoulda-matchers

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

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

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

最佳答案

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

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

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

rspec spec/models/article_spec.rb

关于ruby-on-rails - 使用 rspec3 测试 has_many 和 shoulda-matchers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166851/

相关文章:

ruby-on-rails - Rails-如何在searchkick中添加更多字段以进行过滤?

ruby-on-rails - 设计注册错误

ruby-on-rails - Rails 验证错误后如何保留文件上传字段

ruby-on-rails-4 - 如何从源代码在 Red Hat OS 中安装 FFMPEG?

ruby-on-rails - Rspec parallel_test Controller 规范随机失败

ruby-on-rails - 工头生成的 Upstart 任务找不到文件?

ruby-on-rails-4 - PG pg_ext导轨中的加载错误

ruby-on-rails - 处理完请求后杀死 puma 线程

ruby - 启用 `let` 以在 block 传递给 RSpec 共享示例的情况下分配形式参数

ruby-on-rails - RSpec send_file 测试