【问题标题】:Testing associations with rspec-rails 3.0.1 and shoulda doesn't work测试与 rspec-rails 3.0.1 和 shoulda 的关联不起作用
【发布时间】:2014-06-04 05:21:35
【问题描述】:

目前,使用 rspec-rails (2.14.2),我使用 shoulda (3.5.0) gem 测试我在模型规范中的关联,如下所示:

# app/models/user.rb
class User < ActiveRecord::Base

  belongs_to :school

end

# spec/models/user_spec.rb
describe User do

  it { should belong_to :school }

end

经过一些研究,我试图让关联相关的断言起作用(它们似乎都失败了)。

错误信息:

1) User
     Failure/Error: it { is_expected.to belong_to :school }
     NoMethodError:
       undefined method `belong_to' for #<RSpec::ExampleGroups::School:0x007f8a4c7a68d0>
     # ./spec/models/user.rb:4:in `block (2 levels) in <top (required)>'

所以我的问题是:

  1. 您可以在没有 shoulda gem 的情况下测试关联吗?根据我所看到的“期望”语法,这似乎是不可能的。
  2. should gem 是否与每个人的 rspec 3.0.1 中断?有解决办法吗?

【问题讨论】:

  • 您是否在 Gemfile 中包含了 gem 'shoulda-matchers'
  • 我有“should” gem,但没有“should-matchers”。这是我之前设置的方式。
  • 我认为你应该做到like this
  • 我认为你的关联应该是belongs_to :school(学校是uniq)。也许这是问题的根源
  • 这是一个错误,但看起来与此无关。

标签: ruby-on-rails ruby rspec shoulda


【解决方案1】:

should-matchers 是提供关联、验证和其他匹配器的 gem。

shoulda gem(我们也制作)用于将 shoulda-matchers 与 Test::Unit 一起使用(还提供了一些不错的东西,例如上下文和使用字符串作为测试名称的能力)。但是如果你在 RSpec 上,你会想要使用 shoulda-matchers,而不是 shoulda。

【讨论】:

    【解决方案2】:

    这就是它的工作方式,现在使用 shoulda-matchers gem 和“expect”语法

    describe User, type: :model do
      it { is_expected.to belong_to :school }
    end
    

    【讨论】:

      【解决方案3】:

      我认为您不需要用于基本关联的 gem。

      如果您实际上没有将用户分配到您的学校,您可能会遇到问题。您需要填充外键,而不是只使用关系而不这样做。

      所以你可能需要这样做

      @school = School.new
      @user = User.new
      @school.users << @user
      
      it { should belong_to :school } # within the user block
      

      expect(@user).to belong_to @school
      

      【讨论】:

      • 应该匹配器测试模型中分配的关联。这适用于 rails-rspec 2.x。因此,我的问题是我是否可以使用期望语法进行相同的测试。
      • 我同意,为什么要再输入 3 行 rspec 以确保在要测试的代码中添加 1(例如,belong_to)?
      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 2012-06-17
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多