Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 测试与rspec rails 3.0.1和shoulda的关联性';行不通_Ruby On Rails_Ruby_Rspec_Shoulda - Fatal编程技术网

Ruby on rails 测试与rspec rails 3.0.1和shoulda的关联性';行不通

Ruby on rails 测试与rspec rails 3.0.1和shoulda的关联性';行不通,ruby-on-rails,ruby,rspec,shoulda,Ruby On Rails,Ruby,Rspec,Shoulda,目前,使用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 #app/models/user.r

目前,使用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
#app/models/user.rb
类用户
经过一些研究,我试图让关联相关的断言起作用(它们似乎都失败了)

错误消息:

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)用户
失败/错误:它{应该属于学校}
命名错误:
未定义的方法“属于”#
#./spec/models/user.rb:4:in'block(2层)in'
因此,我的问题是:

  • 你能在没有shoulda gem的情况下测试关联吗?根据我所看到的“expect”语法,这似乎是不可能的
  • 对于每个人来说,shoulda gem是否都应该与rspec 3.0.1决裂?有解决办法吗

  • 我不相信你需要宝石来做基本的联想

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

    所以你可能需要这样做

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

    shoulda matchers是提供关联、验证和其他匹配程序的gem


    shoulda gem(我们也制作)用于将shoulda匹配器与Test::Unit一起使用(还提供了一些不错的功能,比如上下文和使用字符串作为测试名称的能力)。但是,如果您使用的是RSpec,您将希望使用shoulda matchers,而不是shoulda。

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


    您是否在Gemfile中包含了
    gem'shoulda matchers'
    ?我有“shoulda”gem,但没有“shoulda matchers”。这是我以前建立它的方式。我认为你应该这样做。我认为你的协会应该属于:学校(学校是uniq)。也许这是问题的根源这是一个错误,但看起来错误与此无关。匹配器应该在模型中分配关联时测试关联。这在rails rspec 2.x上运行良好。因此,我的问题是,我是否可以使用expect语法进行相同的测试。我同意,为什么还要再键入3行rspec,以确保您在测试的代码中添加1行(例如,归属)?
    expect(@user).to belong_to @school
    
    describe User, type: :model do
      it { is_expected.to belong_to :school }
    end