检查是否从实际请求或控制器规范中调用了控制器的方法?

时间:2012-08-13 18:13:01

标签: ruby-on-rails ruby testing rspec

我的模型Position包含字段started_atended_at,两者都是datetime字段。由于两者的日期部分必须相同,因此datetime_select有一个started_at表单字段,而time_select ignore_date: true只有一个ended_at。在create方法中,我想将started_at的日期值分配给ended_at,如下所示:

params[:position]["ended_at(1i)"] = params[:position]["started_at(1i)"]
params[:position]["ended_at(2i)"] = params[:position]["started_at(2i)"]
params[:position]["ended_at(3i)"] = params[:position]["started_at(3i)"]

但这破坏了我的控制器规格,因为我直接分配了值:

describe "POST create" do
  describe "with valid params" do
    it "creates a new Position" do
      expect {
        post :create, {:position => valid_attributes}, valid_session
      }.to change(Position, :count).by(1)
    end
  end
end

所以我最终得到了这个,但我不确定这是否是一个合理的解决方法:

if params[:position]["ended_at(1i)"].nil? and not params[:position]["started_at(1i)"].nil? # We have to check this because in the controller specs we assign the params directly (not in this crazy xxx_at(yi) form for dates), so by checking this we know that the data was sent through the form
  params[:position]["ended_at(1i)"] = params[:position]["started_at(1i)"]
  params[:position]["ended_at(2i)"] = params[:position]["started_at(2i)"]
  params[:position]["ended_at(3i)"] = params[:position]["started_at(3i)"]
end

也许有更好的解决方案?感谢您的意见。

3 个答案:

答案 0 :(得分:1)

如果控制器期望特定格式的属性,那么规范应该以该格式提供它们。调整valid_attributes,使其以与表单相同的方式分隔日期和时间元素,并且规范应该通过。

答案 1 :(得分:0)

为结束日期/时间设置单独的日期和时间列是不是更容易?

然后有类似的东西:

models / position.rb

before_create :set_end_date

def set_end_date
  self[:end_date] = self[:started_at].to_date
end

<强>规格/控制器/ position_controller_spec.rb

describe "POST Create" do
  describe "with valid attr" do
     it "should create a new Position" do
       lambda do
         post :create, position: valid_attributes, valid_session
       end.should change(Position, :count).by(1)
     end
  end
end

答案 2 :(得分:0)

您可以查看Rails.env.test?