我正在尝试为People Controller编写我的第一个规范 如有必要,使用mongoid(2.0.1),rspec(2.5.0),mongoid-rspec(1.4.2)和制作(0.9.5)。
(注释:组织模型模拟继承自Person模型)
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),我的控制器很干,并且在开发模式下工作正常。
class PeopleController < InheritedResources::Base
actions :index
end
任何想法我做错了Mongoid::Criteria
对象?
提前致谢
答案 0 :(得分:1)
我遇到了同样的问题,但在捆绑mongoid-rspec之后问题就消失了!
答案 1 :(得分:0)
遗憾的是我遇到了同样的问题,我能想出的唯一解决办法就是把它放在控制器中:
def index
@people = Person.all.to_a
end
to_a
方法会将Mongoid::Criteria
对象转换为数组。这种方式对我有用,但我不知道如何使用inherited_resources来实现它。
答案 2 :(得分:0)
就个人而言,我放弃了使用存根测试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
答案 3 :(得分:0)
我最近碰到了类似的问题,我的控制器按预期返回,但我的rspec中的分配(:主题)失败(超过实际的项目返回)。
这本质上是由于rspec分配无法加载通过Inherited Resources获取的实际集合资源。
通过使用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
希望这有帮助。