使用Rspec测试“Post create”
我正在尝试用Rspec测试“Post create”动作。 代码如下:
def valid_attributes { :zone => Flymgr::Zone.new(:countries => Flymgr::ZoneCountry.first, :name => 'USA', :description => 'USA Flight', :zipcodes => ''), :price => '100.00', :class => 'first', } end def valid_session {} end before(:each) do @request.env["devise.mapping"] = Devise.mappings[:admin] admin = FactoryGirl.create(:admin) sign_in admin end describe "POST create" do describe "with valid params" do it "creates a new Flymgr::Rule" do expect { post :create, {:Flymgr_rule => valid_attributes} }.to change(Flymgr::Rule, :count).by(1) end
表单的必需属性之一是“区域”,这是一个下拉框,下拉列表的选项是使用不同的表单创建的。 我不知道如何使用Rspec创建表单条目。 如您所见,我试图从不同的控制器Flymgr::Zone.new
调用一个方法。 我不认为这是有效的,它正在打破我的考验。
谁能建议最好的方法来做到这一点? 也许我应该使用FactoryGirl来创建区域和规则条目?
你的请求参数hash有一个对象作为值:zone,当你发布它只是’to_s’-ed,这不太可能你想要的。
通常,最佳做法是使用工厂女孩来构建对象,并使用attributes_for策略为post请求参数化其属性: 测试“创建”控制器操作的正确方法是什么?
您的问题是建议该关联是belongs_to,因此您只需要发布一个ID。 请注意,目前,FactoryGirl不会为关联创建任何属性。 如果规则的工厂定义负责区域关联,则可以使用此解决方法:
FactoryGirl.build(:flymgr_rule).attributes
还包括zone_id但是,您需要排除不需要的参数。 (“id”,“created_at”,“updated_at”等)。
因此,您可能最好以有效的发布请求中的方式显式插入区域的参数哈希信息。
在factorygirl属性和关联上阅读此主题: https : //github.com/thoughtbot/factory_girl/issues/359
正如指南所指出:
# Returns a hash of attributes that can be used to build a User instance attrs = FactoryGirl.attributes_for(:user)
- 测试cancanfunction并获得MassAssignmentSecurity :: Error
- Factory Girl + Rspec给出以下错误:ActionView :: Template :: Error :(对象id)不是id值
- FactoryGirl关联模型故障:“SystemStackError:堆栈级别太深”
- 我如何分享我在创业板上的工厂并在其他项目中使用它?
- 如何使用attr_accessible创建工厂?
- 在FactoryGirl中查找_or_initialize_by
- 为rails中的自引用关联构建工厂
- 如何在factory_girl中构建/创建多对多关联?
- 工厂女孩 – 为什么记录会不断创建?