我想解决一个问题,我的rspec测试创建一个对象,但计数似乎并没有改变我的任何尝试。我确信我错过了一些非常基本的东西。Rspec不会改变创建
这里是我的RSpec:
before do
login_account_admin(user)
@group = Factory(:group, :code => "GR_111", :description => "description for GR_111")
Group.stub!(:find).and_return(@group)
end
describe "#create" do
it "should create a new group object" do
group_params = {:code => "NEW_GROUP", :description => "description for NEW_GROUP"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to change(Group, :count).by(1)
end
it "should not create a new group object with invalid code format" do
group_params = {:code => "invalid", :description => "description for invalid code name group"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to_not change(Group, :count)
end
end
“代码” 参数只能包含大写字母A到Z,0-9和_
这里是#创建控制器方法定义
def create
@group = Group.new(params[:cdb_group])
respond_to do |format|
if params[:button] == "cancel"
format.js { render "hide_new"}
elsif @group.save
format.js {
render 'show_new_group'
}
format.html { redirect_to(some_path(@service), :notice => 'Group was successfully created.') }
format.xml { head :ok }
end
end
end
下面是组型号:
class Group < ActiveRecord::Base
validates_uniqueness_of :code
validates_presence_of :code, :description
validates_format_of :code, :without => /[^A-Z0-9_]/ , :message => 'can only contain uppercase letters A to Z, 0-9 and _'
end
每当我试图运行rspec的测试中,我得到以下错误: -
1) GroupsController User As Account Admin goes to #create should create a new group object
Failure/Error: expect {
count should have been changed by 1, but was changed by 0
# ./spec/controllers/groups_controller_spec.rb:51
2) GroupsController User As Account Admin goes to #create should not create a new group object with invalid code format
Failure/Error: expect {
count should not have changed, but did change from 2 to 1
# ./spec/controllers/groups_controller_spec.rb:58
在这方面的任何帮助,将不胜感激?
需要更多的细节。 Group模型的外观如何。它是否有验证失败。你确定你的测试没有正常工作,你的代码实际上是错误的,测试指出了这一点? – cpjolicoeur
我敢打赌,你可以在阅读本文后自行解决它:http://nofail.de/2013/10/debugging-rails-applications-in-development/另一个提示,总是实现'else'部分 – phoet
Hi @cpjolicoeur :我已经更新了上面的问题,以表明团队模型如何。是的,代码实际上是正确的,因为它已经通过浏览器成功测试过了,我不会遇到任何错误。 实现了else部分。为了简洁起见,我没有把它列入上面。 – aliibrahim