【问题标题】:Can't save and read Rails variables in Rspec file无法在 Rspec 文件中保存和读取 Rails 变量
【发布时间】:2013-09-22 02:57:24
【问题描述】:

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

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

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

非常感谢!

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多