无法在Rspec文件中保存和读取Rails变量

时间:2013-09-21 18:48:33

标签: ruby-on-rails rspec rspec-rails

我使用

添加了用户模型的订购
default_scope order: 'users.surname ASC'

一切正常。

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

不幸的是,它会出错。虽然,也有类似的测试,但它们运行良好。

以下是exerpts:

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!工作正常。

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

非常感谢!

1 个答案:

答案 0 :(得分:1)

问题是你没有在it块内执行测试操作,但你应该这样做。 e.g:

  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