单元测试 - Mongoid,Rspec和Assigns(:p eople)问题



我正在尝试为人员控制器编写我的第一个规范如有必要,请使用mongoid(2.0.1),rspec(2.5.0),mongoid-rspec(1.4.2)和制造(0.9.5)。

(注:模拟的组织模型继承自人模型)

describe PeopleController do
  describe "as logged in user" do
    before (:each) do
      @user = Fabricate(:user)
      sign_in @user
    end
    describe "GET 'index'" do
      def mock_person(stubs={})
        @mock_person ||= mock_model(Person, stubs).as_null_object
#        @mock_person ||= Fabricate.build(:organization)       
      end
      it "should be successful" do
        get :index
        response.should be_success
      end
      it "assigns all people as @people" do
        Person.stub(:all) { [mock_person] }
        get :index
        assigns(:people).should eq(mock_person)
      end
    end
  end

运行此规范时收到以下错误消息

    1) PeopleController as logged in user GET 'index' assigns all people as @people
       Failure/Error: assigns(:people).should eq(mock_person)
         expected #<Person:0x811b8448 @name="Person_1001">
              got #<Mongoid::Criteria
           selector: {},
           options:  {},
           class:    Person,
           embedded: false>

         (compared using ==)
         Diff:
         @@ -1,2 +1,6 @@
         -#<Person:0x811b8448 @name="Person_1001">
         +#<Mongoid::Criteria
         +  selector: {},
         +  options:  {},
         +  class:    Person,
         +  embedded: false>
       # ./spec/controllers/people_controller_spec.rb:24:in `block (4 levels) in <top (required)>'

由于inherited_resources(1.2.2),我的控制器是DRY的,并且可以在开发模式下正常工作。

class PeopleController < InheritedResources::Base
  actions :index
end

任何想法我做错了什么Mongoid::Criteria反对?

提前致谢

我遇到了同样的问题,但是捆绑mongoid-rspec后问题就消失了!

不幸的是

,我遇到了同样的问题,我能想到的唯一解决方案就是将其放入控制器中:

def index
  @people = Person.all.to_a
end

to_a 方法会将Mongoid::Criteria对象转换为数组。这种方式对我有用,但我不知道你会如何使用inherited_resources。

就个人而言,我放弃了使用存根测试inherited_resources索引操作,并测试返回的条件:

describe "GET 'index'" do
  before do
    get 'index'
  end
  it "returns http success" do
    response.should be_success
  end
  it "should have news" do
    assigns[:news].should be_a(Mongoid::Criteria)
    assigns[:news].selector.should == {}
    assigns[:news].klass.should == News
    assigns[:news].options[:sort].should == [[:created_at, :desc]]
    assigns[:news].options[:limit].should == 10
  end
end

我最近遇到了类似的问题,我的控制器按预期返回,但我的 rspec 中的赋值(:topics)失败(超过返回的实际项目)。

这本质上是由于 rspec 分配无法加载通过继承的资源获取的实际集合资源。

解决方法我使用它来强制加载分配(:主题) 通过使用 logger.info:

class TopicsController < InheritedResources::Base
  def index
    # Needed for rspec assigns() to pass, 
    # since it doesn't evalue inherited_resources resource assignment
    logger.info "Topics: #{@topics.inspect}" if Rails.env.test?
  end
end

希望这有帮助。

相关内容

  • 没有找到相关文章

最新更新