简体   繁体   中英

Can't save and read Rails variables in Rspec file

I added ordering to my User model with

default_scope order: 'users.surname ASC'

Everything work fine.

Then I wanted to add a test case to my spec/models/user_spec.rb file.

Unfortunately, it gives errors. Although, there are similar tests, and they run fine.

Here are 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

In above Rspec file, the describe "users ordered by surname" gives the following error:

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'

I used pretty print (pp) for tracing purposes.

It is strange that in other cases user.save! works fine.

Where is my mistake, what could be wrong here?

Thank you very much!

The problem is that you're not performing the operations of your test within an it block, but you should be. eg:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM