【发布时间】:2014-07-11 01:45:25
【问题描述】:
在 rspec 2 中,我可以做到这一点。
let(:user_1) { create :user_1) # factoryGirl 对象
User.stub(:where).and_return(user_1)
user_1.stub(:where).and_return(user_1)
但在 rspec 3 中,它发生了故障。
let(:user_1) { create :user_1) # factoryGirl 对象
allow(User).to receive(:where).and_return(user_1)
allow(user_1).to receive(:where).and_return(user_1) # 这行出现失败
错误信息是,
失败/错误:allow(product_1).to receive(:where).and_return(product_1)
#<User ..... object description.... >没有实现:哪里
我应该怎么做才能通过这个例子?
----------更新问题----------
在控制器中,
operators = Admin
if !params[:name].blank?
operators = operators.where('adm_name like ?', '%' + params[:name] + '%')
end
if !params[:login_id].blank?
operators = operators.where('adm_login_id like ?', '%' + params[:login_id] + '%')
end
if params[:status] != "all"
operators = operators.where('status=?', params[:status])
end
if !params[:id_check].blank?
operators = operators.where('adm_login_id = ?', params[:id_check])
end
在规范中,
let(:admin) { create :admin }
before do
allow(Admin).to receive(:where).and_return(admin)
allow(admin).to receive(:where).and_return(admin)
end
it 'should be success' do
get :search, params
expect(response).to be_success
end
那么失败信息是,
Failure/Error: allow(admin).to receive(:where).and_return(admin)
#<Admin ... object description ...> does not implement: where
首先,我在before 块中删除了这条语句,
allow(admin).to receive(:where).and_return(admin)
然后我收到一条失败消息,
NoMethodError:
undefined method `first' for #<Admin:0x007f99d2e166d0>
所以我尝试了这个(返回数组),
allow(Admin).to receive(:where).and_return([admin])
然后我收到一条失败消息,
NoMethodError:
undefined method `where' for #<Array:0x007f9a67313e28>
【问题讨论】:
-
你为什么要在模型实例上存根
where方法?where是类方法,不是实例方法。user = User.first; user.where()应该引发 NoMethodError。也许尝试只注释掉那行? -
你的意思是,
user_1.stub(:where)很奇怪?但在 rspec2 中,该代码运行良好。user_1.stub(:where).and_return(user_1)返回user_1 -
Rspec2 可能不会抱怨它,但该存根可能从未以任何方式使用过。
-
感谢您的回答。那么有什么方法可以像
users = users.where('name = ?', params[name])这样的声明吗?我不在乎'where'方法是否有效,我只想得到一个像FactoryGirl或double(模拟对象)这样的假对象
标签: ruby-on-rails rspec rspec3