0

我在我的用户模型中添加了排序

default_scope order: 'users.surname ASC'

一切正常。

然后我想在我的spec/models/user_spec.rb文件中添加一个测试用例。

不幸的是,它给出了错误。虽然,有类似的测试,它们运行良好。

以下是摘录:

require 'spec_helper'

describe User do

  before do
    @user = User.new(name: 'Example', surname: 'User', email: 'user@example.com', 
    password: 'foobar', password_confirmation: 'foobar') 
  end

  subject { @user }

  describe "remember token" do                                                                                                            
    before { @user.save }
    its(:remember_token) {should_not be_blank}
  end

  describe "users ordered by surname" do
    before do
      @user2 = User.create(name: 'Roy', surname: 'McAndy', email: 'pam@exam.com',
      password: 'foobar', password_confirmation: 'foobar') 

      @user3 = User.create(name: 'Roy', surname: 'Andyman', email: 'pamjim@ex.com', 
      password: 'foobar', password_confirmation: 'foobar')
    end

    pp User.all
    pp [@user3, @user2]

    User.all.should == [@user3, @user2]
  end

  describe "with role set to admin" do
    before do
      @user.save!
      @user.update_attribute(:role, "admin")
    end

    it { should be_admin }
  end

在上面的 Rspec 文件中,描述“按姓氏排序的用户”给出了以下错误:

bundle exec rspec
[]
[nil, nil]
/home/xxx/.rvm/gems/ruby-1.9.3-p429/gems/rspec-expectations-2.13.0/lib/rspec/expectations/fail_with.rb:32:in `fail_with': expected: [nil, nil] (RSpec::Expectations::ExpectationNotMetError)
 got: [] (using ==)
Diff:
@@ -1,2 +1,2 @@
-[nil, nil]
+[]

from /home/xxx/.rvm/gems/ruby-1.9.3-p429/gems/rspec-expectations-2.13.0/lib/rspec/matchers/operator_matcher.rb:56:in `fail_with_message'
from /home/xxx/.rvm/gems/ruby-1.9.3-p429/gems/rspec-expectations-2.13.0/lib/rspec/matchers/operator_matcher.rb:94:in `__delegate_operator'

我使用漂亮的打印 (pp) 进行跟踪。

奇怪的是,在其他情况下user.save!工作正常。

我的错误在哪里,这里可能有什么问题?

非常感谢你!

4

1 回答 1

1

问题是您没有在一个it块内执行测试操作,但您应该这样做。例如:

  describe 'default scope' do
    before do
      @user2 = User.create(name: 'Roy', surname: 'McAndy', email: 'pam@exam.com',
      password: 'foobar', password_confirmation: 'foobar') 

      @user3 = User.create(name: 'Roy', surname: 'Andyman', email: 'pamjim@ex.com', 
      password: 'foobar', password_confirmation: 'foobar')
    end

    it 'should order by surname' do
      User.all.should == [@user3, @user2]
    end
  end
于 2013-09-21T18:56:05.303 回答